Joe Camel
Joe Camel

Reputation: 23

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

[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.

Upvotes: 2

Views: 7623

Answers (1)

72DFBF5B A0DF5BE9
72DFBF5B A0DF5BE9

Reputation: 5002

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

Upvotes: 3

Related Questions