C#實現的三種方式實現類比鍵盤按鍵

來源:互聯網
上載者:User

標籤:ext   inf   row   rms   mes   etl   兩種   scan   keyword   

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);        }

C#實現的三種方式實現類比鍵盤按鍵

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.