SendInput代替keybd_event按键支持发送中文
SendInput比keybd_event要方便多了,可以支持发送中文。
#include <atlconv.h>
#pragma comment(lib,"User32.lib")
#pragma comment(lib,"shlwapi.lib")
void SendAscii(wchar_t data, BOOL shift)
{
INPUT input;
memset(input, 0, 2 * sizeof(INPUT));
if (shift)
{
input.type = INPUT_KEYBOARD;
input.ki.wVk = VK_SHIFT;
SendInput(1, input, sizeof(INPUT));
}
input.type = INPUT_KEYBOARD;
input.ki.wVk = data;
input.type = INPUT_KEYBOARD;
input.ki.wVk = data;
input.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(2, input, sizeof(INPUT));
if (shift)
{
input.type = INPUT_KEYBOARD;
input.ki.wVk = VK_SHIFT;
input.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, input, sizeof(INPUT));
}
}
void SendUnicode(wchar_t data)
{
INPUT input;
memset(input, 0, 2 * sizeof(INPUT));
input.type = INPUT_KEYBOARD;
input.ki.wVk = 0;
input.ki.wScan = data;
input.ki.dwFlags = 0x4;//KEYEVENTF_UNICODE;
input.type = INPUT_KEYBOARD;
input.ki.wVk = 0;
input.ki.wScan = data;
input.ki.dwFlags = KEYEVENTF_KEYUP | 0x4;//KEYEVENTF_UNICODE;
SendInput(2, input, sizeof(INPUT));
}
//为方便使用,下面这个函数包装了前两个函数。
void SendKeys(TCHAR *strMsg)
{
short vk;
BOOL shift;
USES_CONVERSION;
wchar_t* data = T2W(strMsg);
int len = wcslen(data);
for(int i=0;i<len;i++)
{
if (data>=0 && data<256) //ascii字符
{
vk = VkKeyScanW(data);
if (vk == -1)
{
SendUnicode(data);
}
else
{
if (vk < 0)
{
vk = ~vk + 0x1;
}
shift = vk >> 8 & 0x1;
if (GetKeyState(VK_CAPITAL) & 0x1)
{
if (data>='a' && data<='z' || data>='A' && data<='Z')
{
shift = !shift;
}
}
SendAscii(vk & 0xFF, shift);
}
}
else //unicode字符
{
SendUnicode(data);
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Sleep(5000);
SendKeys(L"Sysprogram 测试中文");
return 0;
}
页:
[1]