C++ Generating Key Combinations WINAPI (Without MFC)

霸气de小男生 提交于 2019-12-13 06:51:22

问题


I am trying to get my application to output a key combination ( ALT + D ) to focus on Internet explorers address bar, but I am having trouble implementing the code needed. I already have a method to pass 1 key:

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;
}

Can anyone provide some help as to how to achieve a the desired solution ?

SOLUTION:

I managed to solve this issue using the following method:

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;
}

And calling it like so:

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

Where 0x12 is ALT and 0x44 is D.


回答1:


Add an accelerator map to your project resources,Load it into your application at runtime, and in your message loop add a call to TranslateAccelerator before TranslateMessage and DispatchMessage gets a chance to take a look at it.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms646373%28v=vs.85%29.aspx for reference.



来源:https://stackoverflow.com/questions/10532119/c-generating-key-combinations-winapi-without-mfc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!