转自模拟键盘输入
: SendMessage, keybd_event, PostKeybdMessage
目的
最近项目要求在Windows CE下模拟键盘输入,上网搜索了一下,发现有3个API可以用:SendMessage,keybd_event,PostKeybdMessage。
分析
1. SendMessage
(1) 模拟输入字符 - ANSI
::SendMessage(hWnd, WM_CHAR, 'a', 0);
(2) 模拟输入字符 - Unicode
::SendMessage(hWnd, WM_CHAR, L'我', 0)
疑问:用SendMessage是直接向目标窗口发消息,很怀疑它是不是真的在“模拟”。
2. keybd_event
这个API的定义可以在这里找到:http://msdn.microsoft.com/en-us/library/aa453245.aspx
(1) 模拟输入字符 - ANSI
::keybd_event(0x41, 0, 0, 0);
::keybd_event(0x41, 0, KEYEVENTF_KEYUP, 0);
(2) 模拟输入字符 - Unicode
keybd_event的定义说,第一个参数bVk的取值范围只能是[1, 254],而且Windows CE下的keybd_event并不支持KEYEVENTF_UNICODE,而且我也没办法试出用keybd_event输入Unicode字符的方法。
(3) 模拟输入命令
::keybd_event(VK_LCONTROL, 0, 0, 0);
::keybd_event(0x56, 0, 0, 0);
::keybd_event(0x56, 0, KEYEVENTF_KEYUP, 0);
::keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0);
3. PostKeybdMessage
这个API的定义可以在这里找到:http://msdn.microsoft.com/en-us/library/ms911936.aspx
(1) 模拟输入字符
PostKeybdMessage
INT nBufferLength = ::wcslen(lpszBuffer);
UINT* lpStateFlags = new UINT[nBufferLength];
UINT* lpTextBuffer = new UINT[nBufferLength];
for (INT nIndex = 0; nIndex < nBufferLength; nIndex++)
{
lpStateFlags[nIndex] = KeyStateDownFlag;
lpTextBuffer[nIndex] = (UINT)lpszBuffer[nIndex];
}
::PostKeybdMessage(hWnd, 0, lpStateFlags[0], nLength, lpStateFlags, lpTextBuffer);
delete [] lpStateFlags;
delete [] lpTextBuffer;
总结
个人认为
1. 当需要模拟键盘输入命令时,比如Ctrl + V,选择keybd_event;
2. 当需要模拟键盘输入一串字符时,选择PostKeybdMessage;
3. 当需要模拟键盘输入单个字符时,选择keybd_event。
资料:
1. Virtual-Key Codes: http://msdn.microsoft.com/en-us/library/ms927178.aspx