本实例介绍如何在自己的程序里面模拟鼠标的常用操作。 <br><br> 首先启动一个新的项目,在空白的窗体上添加4个TButton组件。添加组件后的窗体如图1所示。<br><br><br>图1 添加组件后的窗体 <br><br> 这4个按钮分别用于模仿鼠标的4个动作——移动鼠标到指定位置、左键单击、左键双击和右键单击。<br><br> 下面以鼠标左键单击为例来说明如何模拟鼠标操作:<br><br>procedure TForm1.btnLClickClick(Sender: TObject);<br>begin<br> SetCursorPos(10,10);<br> mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);<br> mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);<br>end; <br><br> 首先需要通过SetCursorPos函数来设置需要单击的坐标。然后通过mouse_event (MOUSEEVENTF_LEFTDOWN,0,0,0,0)语句在(10,10)坐标处按下鼠标左键。最后不要忘了通过mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0)语句释放鼠标左键。<br><br> 双击的操作可以通过两个连续的单击来实现;鼠标移动的操作可以通过指定mouse_event 函数的第1个参数MOUSEEVENTF_MOVE,第2个和第3个参数为左边来实现;右键单击和左键单击的原理一致,只不过mouse_event函数中的参数分别替换为MOUSEEVENTF_RIGHTDOWN和MOUSEEVENTF_RIGHTUP。<br><br> 程序代码如下:<br><br>unit Unit1;<br>interface<br><br>uses<br> Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,<br> Dialogs, StdCtrls;<br>type<br> TForm1 = class(TForm)<br> btnMove: TButton;<br> btnLClick: TButton;<br> btnLDClick: TButton;<br> btnRClick: TButton;<br> procedure btnMoveClick(Sender: TObject);<br> procedure btnLClickClick(Sender: TObject);<br> procedure btnLDClickClick(Sender: TObject);<br> procedure btnRClickClick(Sender: TObject);<br>private<br> { Private declarations }<br>public<br> { Public declarations }<br>end;<br><br>var<br> Form1: TForm1;<br> implementation<br> {$R *.dfm}<br><br> procedure TForm1.btnMoveClick(Sender: TObject);<br> begin<br> mouse_event(MOUSEEVENTF_MOVE,100,100,0,0);<br> end;<br><br> procedure TForm1.btnLClickClick(Sender: TObject);<br> begin<br> SetCursorPos(10,10);<br> mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);<br> mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);<br> end;<br><br> procedure TForm1.btnLDClickClick(Sender: TObject);<br> begin<br> SetCursorPos(200,200);<br> mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);<br> mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);<br> mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);<br> mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);<br> end;<br><br> procedure TForm1.btnRClickClick(Sender: TObject);<br> begin<br> SetCursorPos(200,200);<br> mouse_event(MOUSEEVENTF_RIGHTDOWN,0,0,0,0);<br> mouse_event(MOUSEEVENTF_RIGHTUP,0,0,0,0);<br> end;<br>end. <br><br> 保存文件,然后按F9键运行程序,程序运行的初始画面如图2所示。<br><br><br>图2 程序运行的初始画面 <br><br> 通过单击窗体上的“移动鼠标”、“左键单击”、“左键双击”和“右键单击”按钮可以分别完成模拟移动鼠标到指定位置、左键单击、左键双击和右键单击等操作。<br><br> 本程序介绍了如何在程序中模拟鼠标的常用操作,这一点在远程监控软件中非常重要,通过mouse_event函数就可以实现远程的鼠标管理和操作。