Mega Code Archive

 
Categories / Delphi / Forms
 

How to move the mouse cursor to the focused control when the form is displayed (from Delphi code)

Title: How to move the mouse cursor to the focused control when the form is displayed (from Delphi code) 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.