上周五在QQ群遇到群友提问的一个问题。问题是这样的:文字识别之后,当点击Excel单元格识别内容自动出现当前单元格中。我提供相关实现思路,使用相关Windows API来实现操作,其中基本思路就是:获取当前鼠标位置=>获取当前位置窗口句柄=>获得当前句柄类=>模拟键盘消息。但遗憾的是他一直没有搞定还一直问,无奈我就直接给他了简单的示例代码。其中使用的Windows API 接口为以下几个:
GetCursorPos
WindowFromPoint
GetClassName
keybd_event
using MouseKeyboardActivityMonitor;
using MouseKeyboardActivityMonitor.WinApi;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinApi;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
MouseHookListener mh;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//安装鼠标钩子
mh = new MouseHookListener(new GlobalHooker());
mh.Enabled = true;
mh.MouseDoubleClick += mh_MouseMoveEvent;
this.textBox1.Text = "Windows API实现键盘粘贴事件";
}
void mh_MouseMoveEvent(object sender, MouseEventArgs e)
{
try
{
Point p = new Point();
WindowsAPI.GetCursorPos(ref p);
IntPtr houseWindow = WindowsAPI.WindowFromPoint(p);
if (houseWindow == IntPtr.Zero)
{
return;
}
StringBuilder sb = new StringBuilder();
WindowsAPI.GetClassName(houseWindow, sb, 255);
if (sb.Length == 0)
{
return;
}
if (!sb.ToString().ToLower().Contains("excel"))
{
return;
}
Clipboard.SetText(string.IsNullOrWhiteSpace(this.textBox1.Text)?"Windows Api": this.textBox1.Text);
System.Threading.Thread.Sleep(100);
WindowsAPI.keybd_event((byte)Keys.ControlKey, 0, 0, 0);//按下
WindowsAPI.keybd_event((byte)Keys.V, 0, 0, 0);
WindowsAPI.keybd_event((byte)Keys.ControlKey, 0, 0x2, 0);//松开
WindowsAPI.keybd_event((byte)Keys.V, 0, 0x2, 0);
}
catch (Exception ex)
{
this.textBox1.Text = ex.Message;
GC.Collect();
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
mh.Enabled = false;
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}
示例下载
示例下载
转载请注明:清风亦平凡 » 使用Windows API向指定窗口发送模拟键盘消息