How to send a keystroke to another process (for example, notepad)?

I have a notebook with 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 the notebook should write A, but nothing will happen.
I tried a message on it WM_DESTROYand it works, but it WM_KEYDOWNdoes not work.
I also did GetLastError(), and it prints error 2 ERROR_FILE_NOT_FOUND.

Why does this not work, and can it be fixed?

+5
source share
2 answers

PostThreadMessage should be used.

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

Two processes must be created by the same user. Otherwise, the function will fail and return ERROR_INVALID_THREAD_ID.

, , SendInput keybd_event .

+3

PID: 2860

, 2860 2680

SendIt (2680);//

+2

All Articles