如何在 C# 中以编程方式生成按键事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1645815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I programmatically generate keypress events in C#?
提问by Dan Vogel
How can I programmatically create an event that would simulate a key being pressed on the keyboard?
如何以编程方式创建一个事件来模拟在键盘上按下的键?
采纳答案by Ray Burns
The question is tagged WPF but the answers so far are specific WinForms and Win32.
这个问题被标记为 WPF,但到目前为止的答案是特定的 WinForms 和 Win32。
To do this in WPF, simply construct a KeyEventArgs and call RaiseEvent on the target. For example, to send an Insert key KeyDown event to the currently focused element:
要在 WPF 中执行此操作,只需构造一个 KeyEventArgs 并在目标上调用 RaiseEvent。例如,要将 Insert key KeyDown 事件发送到当前聚焦的元素:
var key = Key.Insert; // Key to send
var target = Keyboard.FocusedElement; // Target element
var routedEvent = Keyboard.KeyDownEvent; // Event to send
target.RaiseEvent(
new KeyEventArgs(
Keyboard.PrimaryDevice,
PresentationSource.FromVisual(target),
0,
key)
{ RoutedEvent=routedEvent }
);
This solution doesn't rely on native calls or Windows internals and should be much more reliable than the others. It also allows you to simulate a keypress on a specific element.
此解决方案不依赖于本机调用或 Windows 内部结构,并且应该比其他解决方案更可靠。它还允许您模拟特定元素上的按键。
Note that this code is only applicable to PreviewKeyDown, KeyDown, PreviewKeyUp, and KeyUp events. If you want to send TextInput events you'll do this instead:
请注意,此代码仅适用于 PreviewKeyDown、KeyDown、PreviewKeyUp 和 KeyUp 事件。如果你想发送 TextInput 事件,你可以这样做:
var text = "Hello";
var target = Keyboard.FocusedElement;
var routedEvent = TextCompositionManager.TextInputEvent;
target.RaiseEvent(
new TextCompositionEventArgs(
InputManager.Current.PrimaryKeyboardDevice,
new TextComposition(InputManager.Current, target, text))
{ RoutedEvent = routedEvent }
);
Also note that:
另请注意:
Controls expect to receive Preview events, for example PreviewKeyDown should precede KeyDown
Using target.RaiseEvent(...) sends the event directly to the target without meta-processing such as accelerators, text composition and IME. This is normally what you want. On the other hand, if you really do what to simulate actual keyboard keys for some reason, you would use InputManager.ProcessInput() instead.
控件期望接收预览事件,例如 PreviewKeyDown 应该在 KeyDown 之前
使用 target.RaiseEvent(...) 将事件直接发送到目标,无需元处理,例如加速器、文本组合和 IME。这通常是您想要的。另一方面,如果您出于某种原因确实要模拟实际键盘按键,则可以改用 InputManager.ProcessInput()。
回答by Michael Petrotta
I've not used it, but SendKeysmay do what you want.
我没有用过它,但SendKeys可能会做你想做的。
Use SendKeys to send keystrokes and keystroke combinations to the active application. This class cannot be instantiated. To send a keystroke to a class and immediately continue with the flow of your program, use Send. To wait for any processes started by the keystroke, use SendWait.
使用 SendKeys 将击键和击键组合发送到活动应用程序。这个类不能被实例化。要将击键发送到类并立即继续程序流程,请使用发送。要等待按键启动的任何进程,请使用 SendWait。
System.Windows.Forms.SendKeys.Send("A");
System.Windows.Forms.SendKeys.Send("{ENTER}");
Microsoft has some more usage examples here.
微软这里有更多的使用示例。
回答by np-hard
Windows SendMessage APIwith send WM_KEYDOWN.
带有发送WM_KEYDOWN 的Windows SendMessage API。
回答by Rajesh
To produce key events without Windows Forms Context, We can use the following method,
要在没有 Windows 窗体上下文的情况下生成关键事件,我们可以使用以下方法,
[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
sample code is given below:
示例代码如下:
const int VK_UP = 0x26; //up key
const int VK_DOWN = 0x28; //down key
const int VK_LEFT = 0x25;
const int VK_RIGHT = 0x27;
const uint KEYEVENTF_KEYUP = 0x0002;
const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
int press()
{
//Press the key
keybd_event((byte)VK_UP, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
return 0;
}
List of Virtual Keys are defined here.
此处定义了虚拟键列表。
To get the complete picture, please use the below link, http://tksinghal.blogspot.in/2011/04/how-to-press-and-hold-keyboard-key.html
要获取完整图片,请使用以下链接, http://tksinghal.blogspot.in/2011/04/how-to-press-and-hold-keyboard-key.html
回答by Ravid Goldenberg
Easily! (because someone else already did the work for us...)
容易地!(因为其他人已经为我们完成了工作......)
After spending a lot of time trying to this with the suggested answers I came across this codeplex project Windows Input Simulator which made it simple as can be to simulate a key press:
在花了很多时间尝试使用建议的答案之后,我遇到了这个 codeplex 项目Windows Input Simulator,它使模拟按键变得简单:
Install the package, can be done or from the NuGet package manager or from the package manager console like:
Install-Package InputSimulator
Use this 2 lines of code:
inputSimulator = new InputSimulator() inputSimulator.Keyboard.KeyDown(VirtualKeyCode.RETURN)
安装包,可以通过 NuGet 包管理器或包管理器控制台完成,例如:
安装包输入模拟器
使用这 2 行代码:
inputSimulator = new InputSimulator() inputSimulator.Keyboard.KeyDown(VirtualKeyCode.RETURN)
And that's it!
就是这样!
-------EDIT--------
- - - -编辑 - - - -
The project page on codeplex is flagged for some reason, thisis the link to the NuGet gallery.
Codeplex 上的项目页面由于某种原因被标记,这是 NuGet 库的链接。