How to move the mouse cursor to the focused control when the form is displayed

106 39
The ActiveControl property of a Delphi Form object specifies what control has the input focus. You can use this property to set what control is (initially) focused when the form is created and displayed to the user.

If you want to move the mouse cursor to the control with the focus, you can use the next code in the form's OnCreate event handler (the form is named "Form1") :

~~~~~~~~~~~~~~~~~~~~~~~~~
procedure TForm1.FormCreate(Sender: TObject) ;
var
   mousePos : TPoint;
   focusControl : TControl;
begin
   focusControl := ActiveControl;
   if focusControl = nil then
   begin
     focusControl := Controls[0];
   end;

   if focusControl <> nil then
   begin
     mousePos.X := focusControl.Left + focusControl.Width div 2;
     mousePos.Y := focusControl.Top + focusControl.Height div 2;

     Mouse.CursorPos := ClientToScreen(mousePos) ;
   end;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~


The code first checks if the ActiveControl for the Form is assigned. If the ActiveControl was not set at design-time, we'll move the mouse to the control with TabOrder property set to 0 (the first one in the Controls array). Next, the global Mouse object is used to set the position of the mouse using the CursorPos property.

Of course, the code will work if there is at least one control on the form.

Delphi tips navigator:
» Universal solution to formatting values for SQL statements (issued from Delphi code)
« How to get the selected text from a Memo control

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.