Windows Systems Programming: Can a keystroke be sent to an open application that is not the currently active one?

StackOverflow https://stackoverflow.com/questions/593796

Question

I'm a bit rusty on my Windows system programming...

Is it possible for a program to send a keystroke (I'm guessing by SendMessage() api call) to another application, if the (open) target application does not currently have the focus? If it is possible, does it then make the target application become the active application, or does it still remain in the background?

Thanks in advance for any info you may be able to provide!

Was it helpful?

Solution

From memory: Yes, No.

You are looking for WM_KEYDOWN:

PostMessage(hwndOther, WM_KEYDOWN, VK_ENTER, 0);

OTHER TIPS

No, It will not change the focus, unless subsequent calls do setfocus. It will remain the same window order

PostMessage(hwndOther, WM_KEYDOWN, VK_ENTER, 0);

This works for me, but only under Windows XP.

But On Vista and Windows 7 I've too got problem. Propably with UIPI. I am trying to send a message to process from a DLL injected to this process.

How to fix it?

For a directed send of keystrokes, SendInput is the native method of choice, though it is subject to UIPI (integrity level) checks on Vista/2008/W7. You can't send keystrokes to an app that has an IL > yours.

A more general solution for capturing and redirecting input is a global keyboard hook (See the help for SetWindowsHookEx). But this is fairly hairy stuff - you have to cope with how you send the keystrokes on, you affect every process in the system because your code is effectively inserted in the input stream, it involves writing a native DLL... you have to know exactly what you're doing.

We use a global keyboard hook in our system (I wrote it), but we're a special case - a single function emergency call handling system. I wouldn't advise a global hook as a solution in general purpose Windows computing.

You don't need SendInput() or hooks

The answer with PostMessage is wrong.

You must attach remotely your thread. See on Win32 api Group where it's a very classic question (C code, right MS method)

Yes you can send keystrokes, no it won't bring the other window to the top.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top