首先啟動一個新的項目,在空白的窗體上添加4個TButton組件。添加組件後的窗體如圖1所示。
圖1 添加組件後的窗體
這4個按鈕分別用於模仿鼠標的4個動作——移動鼠標到指定位置、左鍵單擊、左鍵雙擊和右鍵單擊。
下面以鼠標左鍵單擊為例來說明如何模擬鼠標操作:
procedure TForm1.btnLClickClick(Sender: TObject);
begin
SetCursorPos(10,10);
mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);
mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);
end;
首先需要通過SetCursorPos函數來設置需要單擊的坐標。然後通過mouse_event (MOUSEEVENTF_LEFTDOWN,0,0,0,0)語句在(10,10)坐標處按下鼠標左鍵。最後不要忘了通過mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0)語句釋放鼠標左鍵。
雙擊的操作可以通過兩個連續的單擊來實現;鼠標移動的操作可以通過指定mouse_event 函數的第1個參數MOUSEEVENTF_MOVE,第2個和第3個參數為左邊來實現;右鍵單擊和左鍵單擊的原理一致,只不過mouse_event函數中的參數分別替換為MOUSEEVENTF_RIGHTDOWN和MOUSEEVENTF_RIGHTUP。
程序代碼如下:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
btnMove: TButton;
btnLClick: TButton;
btnLDClick: TButton;
btnRClick: TButton;
procedure btnMoveClick(Sender: TObject);
procedure btnLClickClick(Sender: TObject);
procedure btnLDClickClick(Sender: TObject);
procedure btnRClickClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnMoveClick(Sender: TObject);
begin
mouse_event(MOUSEEVENTF_MOVE,100,100,0,0);
end;
procedure TForm1.btnLClickClick(Sender: TObject);
begin
SetCursorPos(10,10);
mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);
mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);
end;
procedure TForm1.btnLDClickClick(Sender: TObject);
begin
SetCursorPos(200,200);
mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);
mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);
mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);
mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);
end;
procedure TForm1.btnRClickClick(Sender: TObject);
begin
SetCursorPos(200,200);
mouse_event(MOUSEEVENTF_RIGHTDOWN,0,0,0,0);
mouse_event(MOUSEEVENTF_RIGHTUP,0,0,0,0);
end;
end.
保存文件,然後按F9鍵運行程序,程序運行的初始畫面如圖2所示。
圖2 程序運行的初始畫面
通過單擊窗體上的“移動鼠標”、“左鍵單擊”、“左鍵雙擊”和“右鍵單擊”按鈕可以分別完成模擬移動鼠標到指定位置、左鍵單擊、左鍵雙擊和右鍵單擊等操作。
本程序介紹了如何在程序中模擬鼠標的常用操作,這一點在遠程監控軟件中非常重要,通過mouse_event函數就可以實現遠程的鼠標管理和操作。