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);
}
出处:https://www.cnblogs.com/soundcode/p/9467102.html
关注我】。(●'◡'●)
如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的【因为,我的写作热情也离不开您的肯定与支持,感谢您的阅读,我是【Jack_孟】!
本文来自博客园,作者:jack_Meng,转载请注明原文链接:https://www.cnblogs.com/mq0036/p/10416766.html
【免责声明】本文来自源于网络,如涉及版权或侵权问题,请及时联系我们,我们将第一时间删除或更改!
posted on 2019-02-22 10:20 jack_Meng 阅读(22161) 评论(0) 编辑 收藏 举报