tags:

views:

1096

answers:

2

I am pretty sure the following button-activated form code should raise a Control-F12 in my C# application:

SendKeys("^{F12}");

But it does not appear to go on up to the windows shell and activate another program that is listening for it. My keyboard does work. It seems like the sendkeys is getting intercepted somewhere and not sent on in a way that actually simulates the key stroke. Any help?

+4  A: 

SendKeys is not capable of sending keys outside of the active application.

To really and truly simulate a keystroke systemwide, you need to P/Invoke either keybd_event or SendInput out of user32.dll. (According to MSDN SendInput is the "correct" way but keybd_event works and is simpler to P/Invoke.)

Example (I think these key codes are right... the first in each pair is the VK_ code, and the second is the make or break keyboard scan code... the "2" is KEYEVENTF_KEYUP)

[DllImport("user32.dll")]
private static extern void keybd_event(byte bVk, byte bScan,
    int dwFlags, int dwExtraInfo);

...

keybd_event(0xa2, 0x1d, 0, 0); // Press Left CTRL
keybd_event(0x7b, 0x58, 0, 0); // Press F12
keybd_event(0x7b, 0xd8, 2, 0); // Release F12
keybd_event(0xa2, 0x9d, 2, 0); // Release Left CTRL

The alternative is to activate the application you're sending to before using SendKeys. To do this, you'd need to again use P/Invoke to find the application's window and focus it.

Eric Rosenberger
Can you explain the difference between the make and break codes, and why you chose the ones you did for this? I just ran an app very similar to this (Alt+D instead of Ctrl+F12) where I used break codes in all four calls to keybd_event, and it appears to work as expected.
stack
Actually, the scan code generally isn't used for anything. The OS and applications usually just look at the VK code. So you could probably get away with passing in pretty much anything for that parameter (in fact, many examples on the web just pass in a 0). However, the keyboard driver does provide proper make and break scan codes, so to guarantee 100% compatibility it's probably a good idea to include them just in case some application actually looks at them.
Eric Rosenberger
There are various lists of scan codes on the web, such as http://www.codeproject.com/KB/system/keyboard.aspx, and the break code for a given key is just the make code plus 0x80. There are also API functions to convert back and forth, but I haven't used them.
Eric Rosenberger
To clarify, the make code is the code the keyboard sends when a particular key is pressed, and the break code is the code it sends when that key is released.
Eric Rosenberger
Cool, thanks for the info.
stack
A: 

Eric,

It worked great.

By the way, that's the best response I've had on an open question, and one of the best I've seen. Thanks.

it's also the only question you've asked...
Malfist