How to SendKeys F12 from current .NET form/application

岁酱吖の 提交于 2019-12-03 21:01:35

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!