How to send keydown event to inactive window in C++?

只愿长相守 提交于 2019-12-08 03:26:25

问题


[C++] How to send keydown event to inactive window?

TAB key works fine. But I'm having trouble with other keys such as "Z". Been googling this for a while but haven't found a solution so far.

Virtual key 0x5A should be the correct for letter Z.

#include <iostream>
#include <Windows.h>
#include <string>

LPCSTR Target_window_Name = "Untitled - Notepad"; //<- Has to match window name
HWND hWindowHandle = FindWindow(NULL,Target_window_Name);

int main()
{
   //send TAB DOWN - WORKS FINE
   SendMessage(hWindowHandle,WM_KEYDOWN,0x09,0);
   //send TAB DOWN
   SendMessage(hWindowHandle,WM_KEYUP,0x09,0);

   //send Z DOWN - NOT WORKING
   SendMessage(hWindowHandle,WM_KEYDOWN,0x5A,0);
   //send Z UP
   SendMessage(hWindowHandle,WM_KEYUP,0x5A,0);

   return(0);
}

PS Keydown and Up events are required for what I'm trying to do. Tried searching from several places, but I haven't found a solution so far.


回答1:


Ok. Use Spy++ and hook messages received by Notepad when you press Z key. That way you can simulate/emulate EXACTLY same thing, so it will look like exactly as user pressed Z key. Also you need to find Edit class in Notepad to send messages. So I did this, I ran Spy++, hooked messages, and wrote the same thing. Now it works:

#include <windows.h>
#include <iostream>
#include <string>



int main()
{
    LPCSTR Target_window_Name = "Untitled - Notepad"; //<- Has to match window name
    HWND hWindowHandle = FindWindow(NULL,Target_window_Name);
    HWND EditClass = FindWindowEx(hWindowHandle, NULL, "Edit", NULL);

    SendMessage(EditClass,WM_KEYDOWN,0x5A,0x002C0001);
    SendMessage(EditClass,WM_CHAR,0x7A,0x002C0001);
    SendMessage(EditClass,WM_KEYUP,0x5A,0xC02C0001);

   return(0);
}


来源:https://stackoverflow.com/questions/33508849/how-to-send-keydown-event-to-inactive-window-in-c

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