简体   繁体   中英

How to send keys to a minimized window in C++

I have just started learning C++. At the moment I am stack at a small thing which I cannot find a solution to yet. I hope someone can help me out on this matter.

My goal: I want to send a couple of keystrokes to an running application. But when the application has no focus ie is minimized or what so ever, the keystrokes should still be send to the application.

My problem: When I use the function sendkey() with VK_KEY or what ever (don't remember lol) then it is working BUT only if the window is maximized (focused), but when I try using PostMessage(GameWindow, WM_KEYDOWN, 'G', 0); nothing happens.

I tried it on Notepad, but also on the application which I want it to work but nothing.

I think I need to hook to the process and then send the keys, unfortunately I have no problem with C++ (unless you go totally pro lol) but I have no experience what so ever with hooking and that kind of stuff.

Can anyone send me in the right direction or write me a small tutorial on how to do such a thing, for example with one of the Windows games?

if( amount != 0 )
{
    // bring the window to the front
    HWND GameWindow = FindWindow(0, L"Naamloos - Kladblok");
    SetForegroundWindow(GameWindow);

    // execute the loop
    for( int i = 0; i < amount; i++ ){
    // not the last loop so add a pause at the end
    if( i < (amount-1))
    {
        PostMessage(GameWindow, WM_KEYDOWN, 'G', 0);
        PostMessage(GameWindow, WM_KEYUP, 'G', 0);
        Sleep(2000);
    }
    // last loop so dont add a pause at the end
    else
    {
        PostMessage(GameWindow, WM_KEYDOWN, 'G', 0);
        PostMessage(GameWindow, WM_KEYUP, 'G', 0);
    }
    }
}

The way a Win32 application behaves to Windows messages is completely at its own discretion. So it could be that your target window/app is receiving the messages and just choosing to ignore them. You can use Microsoft Spy++ (comes with Visual Studio) to watch the target apps message queue and see what it receives.

For what its worth, Notepad (v5.1) chooses to listen to WM_CHAR messages (instead of WM_KEYDOWN/WM_KEYUP), even when minimized (sample code below).

#include "stdafx.h"
#include "Windows.h"

int _tmain(int argc, _TCHAR* argv[])
{
    HWND hwndWindowTarget;
    HWND hwndWindowNotepad = FindWindow(NULL, L"Untitled - Notepad");
    if (hwndWindowNotepad)
    {
        // Find the target Edit window within Notepad.
        hwndWindowTarget = FindWindowEx(hwndWindowNotepad, NULL, L"Edit", NULL);
        if (hwndWindowTarget)
        {
            PostMessage(hwndWindowTarget, WM_CHAR, 'G', 0);
        }
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM