5

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?

Filburt
  • 17,626
  • 12
  • 64
  • 115
SmRndGuy
  • 1,719
  • 5
  • 30
  • 49
  • possible duplicate of [Create an On-screen Keyboard](http://stackoverflow.com/questions/4944621/create-an-on-screen-keyboard), http://stackoverflow.com/questions/1220820/how-do-i-send-key-strokes-to-a-window-without-having-to-activate-it-using-window?rq=1, and countless others. – tenfour Aug 23 '12 at 21:11
  • Try using SendInput http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx – jsist Aug 24 '12 at 12:35
  • You are sending fake input to the notepad window, while you should be sending it to the editbox contained into it. – Matteo Italia Aug 24 '12 at 15:09
  • See also http://stackoverflow.com/questions/10407769/directly-sending-keystrokes-to-another-process-via-hooking – rogerdpack Jun 23 '15 at 00:24

2 Answers2

3

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.

oldmonk
  • 739
  • 4
  • 10
3

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

Lorenzo Dematté
  • 7,638
  • 3
  • 37
  • 77
Kurt
  • 31
  • 2