C#實現的三種方式實現模擬鍵盤按鍵


1.System.Windows.Forms.SendKeys

組合鍵:Ctrl = ^ 、Shift = + 、Alt = % 
模擬按鍵:A

        private void button1_Click(object sender, EventArgs e) { textBox1.Focus(); SendKeys.Send("{A}"); }

模擬組合鍵:CTRL + A

        private void button1_Click(object sender, EventArgs e) { webBrowser1.Focus(); SendKeys.Send("^{A}"); }

 

SendKeys.Send // 異步模擬按鍵(不阻塞UI)

SendKeys.SendWait // 同步模擬按鍵(會阻塞UI直到對方處理完消息后返回)

//這種方式適用於WinForm程序,在Console程序以及WPF程序中不適用

2.keybd_event

DLL引用

        [DllImport("user32.dll", EntryPoint = "keybd_event", SetLastError = true)] public static extern void keybd_event(Keys bVk, byte bScan, uint dwFlags, uint dwExtraInfo);

 

模擬按鍵:A

        private void button1_Click(object sender, EventArgs e) { textBox1.Focus(); keybd_event(Keys.A, 0, 0, 0); }

模擬組合鍵:CTRL + A

        public const int KEYEVENTF_KEYUP = 2; private void button1_Click(object sender, EventArgs e) { webBrowser1.Focus(); keybd_event(Keys.ControlKey, 0, 0, 0); keybd_event(Keys.A, 0, 0, 0); keybd_event(Keys.ControlKey, 0, KEYEVENTF_KEYUP, 0); }

3.PostMessage

上面兩種方式都是全局范圍呢,現在介紹如何對單個窗口進行模擬按鍵

模擬按鍵:A / 兩次

        [DllImport("user32.dll", EntryPoint = "PostMessageA", SetLastError = true)] public static extern int PostMessage(IntPtr hWnd, int Msg, Keys wParam, int lParam); public const int WM_CHAR = 256; private void button1_Click(object sender, EventArgs e) { textBox1.Focus(); PostMessage(textBox1.Handle, 256, Keys.A, 2); }

 

模擬組合鍵:CTRL + A

   如下方式可能會失效,所以最好采用上述兩種方式1
        public const int WM_KEYDOWN = 256; public const int WM_KEYUP = 257; private void button1_Click(object sender, EventArgs e) { webBrowser1.Focus(); keybd_event(Keys.ControlKey, 0, 0, 0); keybd_event(Keys.A, 0, 0, 0); PostMessage(webBrowser1.Handle, WM_KEYDOWN, Keys.A, 0); keybd_event(Keys.ControlKey, 0, KEYEVENTF_KEYUP, 0); }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM