1

I'm a beginner in C++.

I want to write a program that auto press a key. In this case, I mean send a key pressed event to the foreground window just like we press then release one key on the keyboard, not just send text of this key to the window.

So I write some code like this:

#include <iostream>
#include <windows.h>
using namespace std;

int main(int argc, const char* argv[])
{
    do
    {
        HWND hwnd = GetForegroundWindow();
        SendMessage(hwnd, WM_KEYDOWN, 0x31, 0);//key 1
        SendMessage(hwnd, WM_KEYUP, 0x31, 0);
        Sleep(1000);
    } while (true);
    return 0;
}

But this code doesn't seem to work. Could you tell me what's wrong with my code.

Thanks a lot and excuse me for my bad English.

Linh
  • 46
  • 4
  • 1
    Have you tested whether the returned window is NULL? It probably is. This is a console application, not a windowed application. There is no `WinMain` entry point, nor is there any message pump to receive the messages you are sending. – paddy Jul 06 '15 at 06:01
  • 1
    If you know window class or name, is better Findwindow function. https://msdn.microsoft.com/es-es/library/windows/desktop/ms633499%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 – Kike Pérez Jul 06 '15 at 06:02
  • #paddy tks, but i didnt really get you in case console app or window app, i just want to send key pressed event to the specified app, and dont care what this app doing with this event – Linh Jul 06 '15 at 06:11
  • #KikePerez tks, i will try this one – Linh Jul 06 '15 at 06:11
  • 2
    Check out this answer: http://stackoverflow.com/questions/1220820/how-do-i-send-key-strokes-to-a-window-without-having-to-activate-it-using-window .. TL;DR you don't want to use `SendMessage`, you want `SendInput` .. Would recommend closing this question as it's pretty similar to many others (i.e. 'WinAPI send key') . – txtechhelp Jul 06 '15 at 06:30

0 Answers0