模拟键盘我们用Keybd_event这个api函数,模拟鼠标按键用mouse_event函数。在VC里调用api函数是既简单又方便不过的事了。
首先介绍一下Keybd_event函数。Keybd_event能触发一个按键事件,也就是说回产生一个WM_KEYDOWN或WM_KEYUP消息。
当然也可以用产生这两个消息来模拟按键,但是没有直接用这个函数方便。Keybd_event共有四个参数,第一个为按键的虚拟键值,
如回车键为vk_return, tab键为vk_tab。第二个参数为扫描码,一般不用设置,用0代替就行第三个参数为选项标志,如果为
keydown则置0即可,如果为keyup则设成"KEYEVENTF_KEYUP",第四个参数一般也是置0即可。用如下代码即可实现模拟按下键,
其中的XX表示XX键的虚拟键值,在这里也就是各键对应的键码,如'A'=65
keybd_event(65,0,0,0);
keybd_event(65,0,KEYEVENTF_KEYUP,0);
...
mouse_event最好配合SetCursorPos(x,y)函数一起使用,与Keybd_event类似,mouse_event有五个参数,第一个为选项标志,
为MOUSEEVENTF_LEFTDOWN时表示左键按下为MOUSEEVENTF_LEFTUP表示左键松开,向系统发送相应消息。第二三个参数分别表示x,y
相对位置,一般可设为0,0,第四五个参数并不重要,一般也可设为0,0。若要得到Keybd_event和mouse_event函数的更详细的用法,
可以查阅msdn或delphi帮助。
下面是关于mouse_event的示例代码:
POINT lpPoint;
GetCursorPos(&lpPoint);
SetCursorPos(lpPoint.x, lpPoint.y);
mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);
mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);
上面的代码表示鼠标的双击,若要表示单击,用两个mouse_event即可(一次放下,一次松开)。
注意,不管是模拟键盘还是鼠标事件,都要注意还原,即按完键要松开,一个keydown对应一个keyup;
鼠标单击完也要松开, 不然可能影响程序的功能。
好了,希望本文能让你对模拟键盘和鼠标按键有个初步的了解,如果想更深入的了解可以查阅msdn在线帮助,
并多多动手实践,也许会对你有很大的帮助。
虚拟键码 :
vk_LButton = $01;
vk_RButton = $02;
vk_Cancel = $03;
vk_MButton = $04;
{ NOT contiguous with L &
RBUTTON }
vk_Back = $08;
vk_Tab = $09;
vk_Clear = $0C;
vk_Return = $0D;
vk_Shift = $10;
vk_Control = $11;
vk_Menu = $12;
vk_Pause = $13;
vk_Capital = $14;
vk_Escape = $1B;
vk_Space = $20;
vk_Prior = $21;
vk_Next = $22;
vk_End = $23;
vk_Home = $24;
vk_Left = $25;
vk_Up = $26;
vk_Right = $27;
vk_Down = $28;
vk_Select = $29;
vk_Print = $2A;
vk_Execute = $2B;
vk_SnapShot = $2C;
{ vk_Copy = $2C not used by keyboards }
vk_Insert = $2D;
vk_Delete = $2E;
vk_Help = $2F;
{ vk_A thru vk_Z are the same as their ASCII equivalents: 'A' thru 'Z' }
{ vk_0 thru vk_9 are the same as their ASCII equivalents: '0' thru '9' }
vk_NumPad0 = $60;
vk_NumPad1 = $61;
vk_NumPad2 = $62;
vk_NumPad3 = $63;
vk_NumPad4 = $64;
vk_NumPad5 = $65;
vk_NumPad6 = $66;
vk_NumPad7 = $67;
vk_NumPad8 = $68;
vk_NumPad9 = $69;
vk_Multiply = $6A;
vk_Add = $6B;
vk_Separator = $6C;
vk_Subtract = $6D;
vk_Decimal = $6E;
vk_Divide = $6F;
vk_F1 = $70;
vk_F2 = $71;
vk_F3 = $72;
vk_F4 = $73;
vk_F5 = $74;
vk_F6 = $75;
vk_F7 = $76;
vk_F8 = $77;
vk_F9 = $78;
vk_F10 = $79;
vk_F11 = $7A;
vk_F12 = $7B;
vk_F13 = $7C;
vk_F14 = $7D;
vk_F15 = $7E;
vk_F16 = $7F;
vk_F17 = $80;
vk_F18 = $81;
vk_F19 = $82;
vk_F20 = $83;
vk_F21 = $84;
vk_F22 = $85;
vk_F23 = $86;
vk_F24 = $87;
vk_NumLock = $90;
vk_Scroll = $91;