繁体   English   中英

WPF发送Ctrl+Key事件

[英]WPF sending Ctrl plus Key event

我正在使用以下代码

private void Send(Key key)
{
    if (Keyboard.PrimaryDevice != null)
    {
        if (Keyboard.PrimaryDevice.ActiveSource != null)
        {
            var e1 = new System.Windows.Input.KeyEventArgs(
                Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, key)
            { RoutedEvent = Keyboard.KeyDownEvent };
            bool b = InputManager.Current.ProcessInput(e1);
        }
    }
}

发送一个按键事件,重新映射我在键盘上按下的实际按键。

例如这里:

private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.PageDown)
    {
        e.Handled = true;
        Send(Key.Right);
    }

我正在将页面重新映射为向右箭头。

如何发送 Control 和右箭头Ctrl + 一起按下?

基本上答案已经在这里(随意关闭重复的问题)。

请注意,在我的情况下,我需要定义

    public const int VK_LCONTROL = 0xA2; //Left CONTROL key
    public const int VK_RIGHT = 0x27; //Right Arrow

所以我只是做

keybd_event(VK_LCONTROL, 0, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event(VK_RIGHT, 0, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event(VK_RIGHT, 0, KEYEVENTF_KEYUP, 0);
keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0);

其中keybd_event在链接的答案中定义( using System.Runtime.InteropServices;等...)。

公共存储库中的完整源代码(评论了另一个替代解决方案)。

或使用现成的 github 项目为 .Net、 Windows 输入模拟器

它还通过编组使用“user32.dll”函数

private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.PageDown)
    {
        e.Handled = true;
        var myInputSimulator = new InputSimulator();
        myInputSimulator.Keyboard.KeyDown(VirtualKeyCode.CONTROL);
        myInputSimulator.Keyboard.KeyPress(VirtualKeyCode.RIGHT);
     }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM