Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 723
SmRndGuy Avatar asked Aug 23 '12 21:08

SmRndGuy


2 Answers

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.

like image 167
oldmonk Avatar answered Sep 21 '22 18:09

oldmonk


I got a notepad which has a PID: 2860

Couldn't help noticing that you are saying 2860 and calling 2680

SendIt(2680); //notepad ID

like image 40
Kurt Avatar answered Sep 21 '22 18:09

Kurt