2007. november 26., hétfő

Simulate Mouse Clicks and Moves


Problem/Question/Abstract:

How can I simulate mouse clicks in my application written in Delphi?

Answer:

You can easily simulate mouse clicks or moves with the mouse_event-function. You can find more information about the parameters and flags for this function in the Delphi-helpfile.

This function can be useful when you can not control other applications by OLE or something like that.

Example:

You want to start an application, and doubleclick on an item which is at x,y-position 300,400 in this application. Put a TTimer on your form, set it to Disabled and try this example code:

procedure TForm1.FormCreateOrWhatever;
begin
  winexec('myexternalapplication.exe', sw_shownormal); // start app
  timer1.interval := 2000; // give the app 2 secs to start up
  timer1.enabled := true; // start the timer
end;

procedure TForm1.Timer1Timer(Sender: TObject);
var
  point: TPoint; // point-structure needed by getcursorpos()
begin
  getcursorpos(point); // get current mouse position
  setcursorpos(300, 400); // set mouse cursor to menu item or whatever
  mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); // click down
  mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); // +click up = double click
  setcursorpos(point.x, point.y); // set cursor pos to origin pos
  timer1.enabled := false; // stop
end;

The timer is needed to give the application time to start up. Be sure you don't move the mouse while mouse_event is executed. That's it!

Nincsenek megjegyzések:

Megjegyzés küldése