RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1403263
Accepted
denisnumb
denisnumb
Asked:2022-06-24 04:16:27 +0000 UTC2022-06-24 04:16:27 +0000 UTC 2022-06-24 04:16:27 +0000 UTC

C# WPF:如何以编程方式按下键盘快捷键?

  • 772

WPF 应用程序有一个在按下+Test()组合键时调用的方法。CTRLG

test方法调用有效,因为字符串从方法的第一行打印到控制台。


CTRL该方法应该以编程方式按下+组合键A以突出显示任何输入字段中的文本,但事实并非如此。

我尝试了两种方法:


第一:接受字符串的方法System.Windows.Forms.SendKeys.SendWait(),其中^- CTRL- 根据文档

private void Test(object sender, EventArgs e)
{
    Console.WriteLine("test");
    SendKeys.SendWait("^A");
}

但是,没有紧迫感。


第二:通过实施user32.dll,解决方案取自这里:

[DllImport("user32.dll", SetLastError = true)]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
public static void PressKey(Keys key, bool up)
{
    const int KEYEVENTF_EXTENDEDKEY = 0x1;
    const int KEYEVENTF_KEYUP = 0x2;
    if (up)
        keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, (UIntPtr)0);
    else
        keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr)0);
}

private void Test(object sender, EventArgs e)
{
    Console.WriteLine("test");
    PressKey(Keys.ControlKey, up: false);
    PressKey(Keys.A, up: false);
    PressKey(Keys.A, up: true);
    PressKey(Keys.ControlKey, up: true);
}

但在这种情况下,什么也没有发生。


我的错误是什么?

c# wpf
  • 1 1 个回答
  • 194 Views

1 个回答

  • Voted
  1. Best Answer
    aepot
    2022-06-24T22:22:26Z2022-06-24T22:22:26Z

    keybd_event是一种过时的 Win API 方法,目前的方法是SendInput. 对于第一个,您必须Thread.Sleep(50)在按下和释放键之间实现手动暂停类型,然后它并不总是有效,但它会有效。但是有一个更好的方法。

    其实有一个 NuGet 包InputSimulator,它可以做到这一切,只需安装它并使用一键输出。在内部,它使用相同SendInput的方法,但我已经有自己的现成实现您需要的方法。SendInput顺便说一句,它支持键盘和鼠标模拟。

    赢API

    internal static class NativeMethods
    {
        [Flags]
        public enum KeyboardFlags : uint
        {
            None = 0,
    
            /// <summary>
            /// KEYEVENTF_EXTENDEDKEY = 0x0001 (If specified, the scan code was preceded by a prefix byte that has the value 0xE0 (224).)
            /// </summary>
            ExtendedKey = 1,
    
            /// <summary>
            /// KEYEVENTF_KEYUP = 0x0002 (If specified, the key is being released. If not specified, the key is being pressed.)
            /// </summary>
            KeyUp = 2,
    
            /// <summary>
            /// KEYEVENTF_UNICODE = 0x0004 (If specified, wScan identifies the key and wVk is ignored.)
            /// </summary>
            Unicode = 4,
    
            /// <summary>
            /// KEYEVENTF_SCANCODE = 0x0008 (Windows 2000/XP: If specified, the system synthesizes a VK_PACKET keystroke. The wVk parameter must be zero. This flag can only be combined with the KEYEVENTF_KEYUP flag. For more information, see the Remarks section.)
            /// </summary>
            ScanCode = 8,
        }
    
        [Flags]
        public enum MouseFlags : uint
        {
            /// <summary>
            /// Specifies that movement occurred.
            /// </summary>
            Move = 0x0001,
    
            /// <summary>
            /// Specifies that the left button was pressed.
            /// </summary>
            LeftDown = 0x0002,
    
            /// <summary>
            /// Specifies that the left button was released.
            /// </summary>
            LeftUp = 0x0004,
    
            /// <summary>
            /// Specifies that the right button was pressed.
            /// </summary>
            RightDown = 0x0008,
    
            /// <summary>
            /// Specifies that the right button was released.
            /// </summary>
            RightUp = 0x0010,
    
            /// <summary>
            /// Specifies that the middle button was pressed.
            /// </summary>
            MiddleDown = 0x0020,
    
            /// <summary>
            /// Specifies that the middle button was released.
            /// </summary>
            MiddleUp = 0x0040,
    
            /// <summary>
            /// Windows 2000/XP: Specifies that an X button was pressed.
            /// </summary>
            XDown = 0x0080,
    
            /// <summary>
            /// Windows 2000/XP: Specifies that an X button was released.
            /// </summary>
            XUp = 0x0100,
    
            /// <summary>
            /// Windows NT/2000/XP: Specifies that the wheel was moved, if the mouse has a wheel. The amount of movement is specified in mouseData. 
            /// </summary>
            VerticalWheel = 0x0800,
    
            /// <summary>
            /// Specifies that the wheel was moved horizontally, if the mouse has a wheel. The amount of movement is specified in mouseData. Windows 2000/XP:  Not supported.
            /// </summary>
            HorizontalWheel = 0x1000,
    
            /// <summary>
            /// Windows 2000/XP: Maps coordinates to the entire desktop. Must be used with MOUSEEVENTF_ABSOLUTE.
            /// </summary>
            VirtualDesk = 0x4000,
    
            /// <summary>
            /// Specifies that the dx and dy members contain normalized absolute coordinates. If the flag is not set, dxand dy contain relative data (the change in position since the last reported position). This flag can be set, or not set, regardless of what kind of mouse or other pointing device, if any, is connected to the system. For further information about relative mouse motion, see the following Remarks section.
            /// </summary>
            Absolute = 0x8000,
        }
    
        [StructLayout(LayoutKind.Sequential)]
        public struct KEYBDINPUT
        {
            public ushort virtualKey;
            public ushort scanCode;
            public KeyboardFlags flags;
            public uint timeStamp;
            public IntPtr extraInfo;
        }
    
        [StructLayout(LayoutKind.Sequential)]
        public struct MOUSEINPUT
        {
            public int deltaX;
            public int deltaY;
            public uint mouseData;
            public MouseFlags flags;
            public uint time;
            public IntPtr extraInfo;
        }
    
        [StructLayout(LayoutKind.Sequential)]
        public struct HARDWAREINPUT
        {
            public uint message;
            public ushort wParamL;
            public ushort wParamH;
        }
    
        [StructLayout(LayoutKind.Explicit)]
        public struct InputUnion
        {
            [FieldOffset(0)]
            public MOUSEINPUT mouse;
            [FieldOffset(0)]
            public KEYBDINPUT keyboard;
            [FieldOffset(0)]
            public HARDWAREINPUT hardware;
        }
        public enum InputType : int
        {
            Mouse = 0,
            Keyboard = 1,
            Hardware = 2
        }
        public struct INPUT
        {
            public InputType type;
            public InputUnion union;
        }
    
        public static int SizeOfInput { get; } = Marshal.SizeOf(typeof(INPUT));
    
        [DllImport("user32.dll")]
        public static extern uint SendInput(int nInputs, INPUT[] pInputs, int cbSize);
    }
    

    现在你可以写这个方法

    public static void ModifiedKeyStroke(Key key, ModifierKeys modifiers = ModifierKeys.None)
    {
        static NativeMethods.INPUT BuildINPUT(Key k, NativeMethods.KeyboardFlags flags) => new NativeMethods.INPUT
        {
            type = NativeMethods.InputType.Keyboard,
            union = new NativeMethods.InputUnion { keyboard = new NativeMethods.KEYBDINPUT { virtualKey = (ushort)KeyInterop.VirtualKeyFromKey(k), scanCode = 0, flags = flags, timeStamp = 0, extraInfo = IntPtr.Zero } }
        };
        List<Key> keys = new List<Key>();
        if (modifiers.HasFlag(ModifierKeys.Control)) keys.Add(Key.LeftCtrl);
        if (modifiers.HasFlag(ModifierKeys.Alt)) keys.Add(Key.LeftAlt);
        if (modifiers.HasFlag(ModifierKeys.Shift)) keys.Add(Key.LeftShift);
        if (modifiers.HasFlag(ModifierKeys.Windows)) keys.Add(Key.LWin);
        keys.Add(key);
        NativeMethods.INPUT[] inputs = new NativeMethods.INPUT[keys.Count * 2];
        for (int i = 0; i < keys.Count; i++)
        {
            inputs[i] = BuildINPUT(keys[i], NativeMethods.KeyboardFlags.None);
            inputs[^(i + 1)] = BuildINPUT(keys[i], NativeMethods.KeyboardFlags.KeyUp);
        }
        _ = NativeMethods.SendInput(inputs.Length, inputs, NativeMethods.SizeOfInput);
    }
    

    它看起来很吓人,但这就是微软决定做一些可怕的事情的方式。但它完美无缺。

    如何使用

    Ctrl+C

    ModifiedKeyStroke(Key.C, ModifierKeys.Control);
    

    Ctrl+Shit+Esc

    ModifiedKeyStroke(Key.Escape, ModifierKeys.Control | ModifierKeys.Shift);
    

    F

    ModifiedKeyStroke(Key.F);
    

    顺便说一句,某些组合的使用存在系统限制,例如 using ModifierKeys.Windowsand another type Ctrl+Alt+Del,这禁止了某些应用程序可能在您不知情的情况下更改您的系统密码和其他危险事情的情况。这不能被绕过,如果某些东西不起作用,那么首先要确保这不受 Windows 保护系统的限制。

    • 1

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5