How to send a keystroke to an other process (ex a notepad)?

SmRndGuy picture SmRndGuy · Aug 23, 2012 · Viewed 12.2k times · Source

I got a notepad which has a PID: 2860

#include <iostream>
#include <windows.h>
#include <psapi.h>
using namespace std;
HWND SendIt (DWORD dwProcessID){
    HWND hwnd = NULL;
    do {
         hwnd = FindWindowEx(NULL, hwnd, NULL, NULL);
         DWORD dwPID = 0;
         GetWindowThreadProcessId(hwnd, &dwPID);
         if (dwPID == dwProcessID) {
            cout<<"yay:"<<hwnd<<":pid:"<<dwPID<<endl;//debug
            PostMessage(hwnd,WM_KEYDOWN,'A',1); //send
         }
    } while (hwnd != 0);
    return hwnd; //Ignore that

}
int main()
{
    SendIt(2680); //notepad ID
    return 0;
}

and notepad should write A to it but nothing happens.
I tried WM_DESTROY message on it and it's working but WM_KEYDOWN is not working.
I have also done GetLastError() and it prints error 2 ERROR_FILE_NOT_FOUND.

Why is this not working and is it possible to fix it?

Answer

oldmonk picture oldmonk · Aug 23, 2012

PostThreadMessage should be used.

hThread = GetWindowThreadProcessId(hwnd,&dwPID);  
if (dwPID == dwProcessID && hThread!= NULL ) {
   PostThreadMessage( hThread, WM_KEYDOWN,'A',1);
}

Two process must be created by same user. Otherwise, the function fails and returns ERROR_INVALID_THREAD_ID.

If the other process is active window which is capturing keyboard input, SendInput or keybd_event also can be used to send keystroke event.