在要求输入邮箱的文本域,请填写真实的邮件地址。非真实邮件地址,将收不到回复信息。

使用Windows API向指定窗口发送模拟键盘消息

IT相关 清风 750℃ 0评论

上周五在QQ群遇到群友提问的一个问题。问题是这样的:文字识别之后,当点击Excel单元格识别内容自动出现当前单元格中。我提供相关实现思路,使用相关Windows API来实现操作,其中基本思路就是:获取当前鼠标位置=>获取当前位置窗口句柄=>获得当前句柄类=>模拟键盘消息。但遗憾的是他一直没有搞定还一直问,无奈我就直接给他了简单的示例代码。其中使用的Windows API 接口为以下几个:

GetCursorPos

WindowFromPoint

GetClassName

keybd_event

使用Windows API向指定窗口发送模拟键盘消息-第0张图片

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向指定窗口发送模拟键盘消息

喜欢 (11)or分享 (0)
支付宝扫码打赏 支付宝扫码打赏 微信打赏 微信打赏
头像
发表我的评论
取消评论

CAPTCHA Image
Reload Image
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址