delphifocusselectiondatetimepicker

Delphi: de-focus TDateTimePicker control


I have the following problems with the TDateTimePicker control:

  1. When the form comes up, it's automatically focused. It's my first control on the form, but everything needs to be de-focused on startup. I tried the following:

    procedure TfrmMain.FormShow(Sender: TObject);
    begin
      // ...
      // Defocus everything
      Self.ActiveControl := nil; // Does not work
    end;
    
    
  2. Also, there is a TSpeedButton which should de-focus this control, but pressing it doesn't remove the focus from the TDateTimePicker. (Other controls like a regular TButton do remove it.)

    month selected in DateTimePicker


Solution

  • When the form comes up, it's automatically focused. It's my first control on the form, but everything needs to be de-focused on startup.

    That is a very strange requirement. My gut feeling is that your design is suboptimal. You shouldn't fight the OS and its conventions – you should try to adhere to the norms the users expect on the platform.

    Also, there is a TSpeedButton which should de-focus this control, but pressing it doesn't remove the focus from the TDateTimePicker.

    That's expected, since TSpeedButton is a graphic control, not a windowed control. Hence, a speed button isn't a window (like a regular button, edit box, radio button, checkbox, combo box, list box, list view, etc. is).

    In particular, this means that users cannot move to your button using the keyboard (Tab), so speed buttons make your GUI less accessible and less convenient to use.

    I never use speed buttons for this reason.

    everything needs to be de-focused on startup

    But if you absolutely insist, you can make everything defocused from the beginning.

    You only need to add an OnActivate handler that sets the form's ActiveControl to nil:

    procedure TForm1.FormActivate(Sender: TObject);
    begin
      ActiveControl := nil
    end;