Search code examples
winapijnauser32

Background Window not getting messages sent through PostMessage()


I'm trying to send a message to a background window using JNA.

However, nothing happens. I thought that maybe this application behaved like Notepad (where you need to find the child windows to actually write text), so I tried sending the message to all child windows as well, but still nothing happens.

Here's my code:

User32 user32 = User32.INSTANCE;

HWND hWnd = user32.FindWindow(null, "MyWindow");

int tid = user32.GetWindowThreadProcessId(hWnd, null);
user32.EnumThreadWindows(tid, new aux(), null);

private class aux implements WNDENUMPROC {

    @Override
    public boolean callback(HWND hwnd, Pointer pointer) {

        User32 user32 = User32.INSTANCE;

        char[] title = new char[1024];
        user32.GetWindowText(hwnd, title, 1024);

        System.out.println(new String(title));

        user32.PostMessage(hwnd, WM_KEYDOWN, new WPARAM(VK_Q), new LPARAM(0));

        user32.PostMessage(hwnd, WM_KEYUP, new WPARAM(VK_Q), new LPARAM(1));

        System.out.println("error: " + Kernel32.INSTANCE.GetLastError());

        return true;
    }
}

The output:

MyChildWindow1 (= MyWindow)
error: 0
MyChildWindow2
error: 0
MyChildWindow3
error: 0

I've tried using PostMessage, PostThreadMessage and SendMessage. None of these worked.

How can I send messages to this application?


Solution

  • You can’t simulate keyboard input with PostMessage. It does work with some applications but not everything because it skips the lower level parts of the input system like hooks and things waiting for QS_KEY. If you still want to hack it this way you could use Spy++ to at least tell if the message is getting posted to the correct window. If it is and it does nothing then you need to look for other options.

    If you are doing simple UI automation then SendInput should be your first choice or MSAA/UIA if the application is not in the foreground or if you need more control.