问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/436430/how-to-sendkeys-f12-from-current-net-form-application