C ++生成组合键WINAPI(不带MFC)

时间:2012-05-10 10:27:59

标签: c++ winapi keypress

我正在尝试让我的应用程序输出一个组合键(ALT + D)以专注于Internet Explorer的地址栏,但我无法实现所需的代码。我已经有了传递1个密钥的方法:

void GenerateKey(int vk, BOOL bExtended) {

KEYBDINPUT  kb = {0};
INPUT       Input = {0};

/* Generate a "key down" */
if (bExtended) { kb.dwFlags  = KEYEVENTF_EXTENDEDKEY; }
kb.wVk  = vk;
Input.type  = INPUT_KEYBOARD;
Input.ki  = kb;
SendInput(1, &Input, sizeof(Input));

/* Generate a "key up" */
ZeroMemory(&kb, sizeof(KEYBDINPUT));
ZeroMemory(&Input, sizeof(INPUT));
kb.dwFlags  =  KEYEVENTF_KEYUP;
if (bExtended) { kb.dwFlags |= KEYEVENTF_EXTENDEDKEY; }
kb.wVk = vk;
Input.type = INPUT_KEYBOARD;
Input.ki = kb;
SendInput(1, &Input, sizeof(Input));

return;
}

任何人都可以提供一些有关如何实现所需解决方案的帮助吗?

SOLUTION:

我设法使用以下方法解决了这个问题:

void GenerateKeyCombination(int vk, int vk2, BOOL bExtended, BOOL bExtended2) {

KEYBDINPUT  kb = {0};
INPUT       Input = {0};
KEYBDINPUT  kb2 = {0};
INPUT       Input2 = {0};

// Generate a "key down" 1
if (bExtended) { kb.dwFlags  = KEYEVENTF_EXTENDEDKEY; }
kb.wVk  = vk;
Input.type  = INPUT_KEYBOARD;
Input.ki  = kb;
SendInput(1, &Input, sizeof(Input));

// Generate a "key down" 2
if (bExtended2) { kb2.dwFlags  = KEYEVENTF_EXTENDEDKEY; }
kb2.wVk  = vk2;
Input2.type  = INPUT_KEYBOARD;
Input2.ki  = kb2;
SendInput(1, &Input2, sizeof(Input2));

// Generate a "key up" 1
ZeroMemory(&kb, sizeof(KEYBDINPUT));
ZeroMemory(&Input, sizeof(INPUT));
kb.dwFlags  =  KEYEVENTF_KEYUP;
if (bExtended) { kb.dwFlags |= KEYEVENTF_EXTENDEDKEY; }
kb.wVk = vk;
Input.type = INPUT_KEYBOARD;
Input.ki = kb;
SendInput(1, &Input, sizeof(Input));

// Generate a "key up" 2
ZeroMemory(&kb2, sizeof(KEYBDINPUT));
ZeroMemory(&Input2, sizeof(INPUT));
kb2.dwFlags  =  KEYEVENTF_KEYUP;
if (bExtended2) { kb2.dwFlags |= KEYEVENTF_EXTENDEDKEY; }
kb2.wVk = vk2;
Input2.type = INPUT_KEYBOARD;
Input2.ki = kb2;
SendInput(1, &Input2, sizeof(Input2));

return;
}

并且这样称呼它:

        GenerateKeyCombination(0x12, 0x44, FALSE, FALSE);

其中0x12是ALT,0x44是D.

1 个答案:

答案 0 :(得分:3)

将加速器映射添加到项目资源,在运行时将其加载到应用程序中,并在消息循环中添加对TranslateAccelerator的调用,然后TranslateMessage和DispatchMessage有机会查看它。

http://msdn.microsoft.com/en-us/library/windows/desktop/ms646373%28v=vs.85%29.aspx供参考。