Winform SendKey

Jiale Xue - MSFT 46,456 信誉分 Microsoft 供应商
2024-05-31T09:00:43.08+00:00

我是一个应用程序并传播。我们从应用程序中选择一个按钮。其次,我们输入小零件,我无法将其连接到钥匙上。即“e”被要求切换,这个e键“o”被审查。

Note:此问题总结整理于: Winform SendKey

Windows 窗体
Windows 窗体
一组用于开发图形用户界面的 .NET Framework 托管库。
113 个问题
0 个注释 无注释
{count} 票

接受的答案
  1. Hui Liu-MSFT 48,571 信誉分 Microsoft 供应商
    2024-05-31T09:27:22.9766667+00:00

    如果即使表单被隐藏,也要运行keydown事件,可以尝试使用全局键盘监控(Hook)来执行。

    下面是一个可以参考的代码示例。

    using System;  
    using System.Runtime.InteropServices;  
    using System.Windows.Forms;  
      
      class KeyboardHook  
        {  
            public event KeyEventHandler KeyDownEvent;  
            public event KeyPressEventHandler KeyPressEvent;  
            public event KeyEventHandler KeyUpEvent;  
      
            public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);  
            static int hKeyboardHook = 0;   
                                           
                                           
            public const int WH_KEYBOARD_LL = 13;     
            HookProc KeyboardHookProcedure;   
      
            [StructLayout(LayoutKind.Sequential)]  
            public class KeyboardHookStruct  
            {  
                public int vkCode;    
                public int scanCode;   
                public int flags;    
                public int time;   
                public int dwExtraInfo;   
            }  
       
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]  
            public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);  
      
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]  
            public static extern bool UnhookWindowsHookEx(int idHook);  
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]  
            public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);  
      
      
            [DllImport("kernel32.dll")]  
            static extern int GetCurrentThreadId();  
      
            [DllImport("kernel32.dll")]  
            public static extern IntPtr GetModuleHandle(string name);  
      
            public void Start()  
            {  
      
                if (hKeyboardHook == 0)  
                {  
                    KeyboardHookProcedure = new HookProc(KeyboardHookProc);  
                    hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, GetModuleHandle(System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName), 0);  
                    
                    if (hKeyboardHook == 0)  
                    {  
                        Stop();  
                        throw new Exception("Failed to install keyboard hook");  
                    }  
                }  
            }  
            public void Stop()  
            {  
                bool retKeyboard = true;  
      
                if (hKeyboardHook != 0)  
                {  
                    retKeyboard = UnhookWindowsHookEx(hKeyboardHook);  
                    hKeyboardHook = 0;  
                }  
      
                if (!(retKeyboard)) throw new Exception("Failed to uninstall keyboard hook!");  
            }  
            [DllImport("user32")]  
            public static extern int ToAscii(int uVirtKey,   
                                             int uScanCode,   
                                             byte[] lpbKeyState,   
                                             byte[] lpwTransKey,   
                                             int fuState);   
      
      
            [DllImport("user32")]  
            public static extern int GetKeyboardState(byte[] pbKeyState);  
      
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]  
            private static extern short GetKeyState(int vKey);  
      
            private const int WM_KEYDOWN = 0x100;//KEYDOWN  
            private const int WM_KEYUP = 0x101;//KEYUP  
            private const int WM_SYSKEYDOWN = 0x104;//SYSKEYDOWN  
            private const int WM_SYSKEYUP = 0x105;//SYSKEYUP  
      
            private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)  
            {  
      
                if ((nCode >= 0) && (KeyDownEvent != null || KeyUpEvent != null || KeyPressEvent != null))  
                {  
                    KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));  
                    // raise KeyDown  
                    if (KeyDownEvent != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))  
                    {  
                        Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;  
                        KeyEventArgs e = new KeyEventArgs(keyData);  
                        KeyDownEvent(this, e);  
                    }  
      
      
                    if (KeyPressEvent != null && wParam == WM_KEYDOWN)  
                    {  
                        byte[] keyState = new byte[256];  
                        GetKeyboardState(keyState);  
      
                        byte[] inBuffer = new byte[2];  
                        if (ToAscii(MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags) == 1)  
                        {  
                            KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]);  
                            KeyPressEvent(this, e);  
                        }  
                    }  
      
      
                    if (KeyUpEvent != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))  
                    {  
                        Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;  
                        KeyEventArgs e = new KeyEventArgs(keyData);  
                        KeyUpEvent(this, e);  
                    }  
      
                }  
                return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);  
            }  
            ~KeyboardHook()  
            {  
                Stop();  
            }  
        }  
    

    您可以在 Form_Load 事件中使用它。

    private void Form1_Load(object sender, EventArgs e)  
            {  
                var k_hook = new KeyboardHook();  
                k_hook.KeyDownEvent += new KeyEventHandler(hook_KeyDown);  
                k_hook.Start();  
            }  
            private void hook_KeyDown(object sender, KeyEventArgs e)  
            {  
      
                if (e.KeyValue >= (int)Keys.A &&e.KeyValue<=(int)Keys.Z )  
                {  
                    System.Windows.Forms.MessageBox.Show(e.KeyCode.ToString());  
                }  
            }  
    

    结果:

    123516-result.gif


    如果回复有帮助,请点击“接受答案”并点赞。

    注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。

    1 个人认为此答案很有帮助。
    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助

你的答案

问题作者可以将答案标记为“接受的答案”,这有助于用户了解已解决作者问题的答案。