C# 三种方式实现模拟键盘按键

413次阅读
一条评论

共计 1530 个字符,预计需要花费 4 分钟才能阅读完成。

模拟按键在.Net 中有三种方式实现。

第一种方式: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 直到对方处理完消息后返回)

第二种方式:keybd_event

模拟按键:A

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

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

上面两种方式都是全局范围呢,现在介绍如何对单个窗口进行模拟按键

模拟按键: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

如下方式可能会失效,所以最好采用上述两种方式

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/smallfa/p/5741351.html

正文完
 0
flames
版权声明:本文于2024-06-11转载自博客园,共计1530字。
转载提示:此文章非本站原创文章,若需转载请联系原作者获得转载授权。
评论(一条评论)
亦朵智库 评论达人 LV.1
2024-08-07 10:56:07 回复

每天学习一点技术

 Windows  Chrome  中国浙江省宁波市联通