阅读背景:

C#程序模拟键盘输入向记事本内添加内容

来源:互联网 
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //第一个与第三个是用于查找窗口句柄的
        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);

        [DllImport("User32.dll ")]
        public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr childe, string strclass, string FrmText);

        [DllImport("USER32.DLL")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        bool a = true;
        private void button1_Click(object sender, EventArgs e)
        {
            Test();
            if (a == true)
            {
                this.txtText.Text = "乐乐…!";
                Form2 for2 = new Form2();
                for2.ShowDialog();
            }
            a = false;
        }
        HotKeys h = new HotKeys();

        private void Form1_Load(object sender, EventArgs e)
        {
            //这里注册了Ctrl+E 快捷键
            h.Regist(this.Handle, (int)HotKeys.HotkeyModifiers.Control, Keys.E, CallBack);
            //MessageBox.Show("注册成功");
        }

        //重载WndProc函数
        protected override void WndProc(ref Message m)
        {
            h.ProcessHotKey(m);//快捷键消息处理
            base.WndProc(ref m);
        }

        //跨越程序输入
        public void Test()
        { 
            const int WM_SETTEXT = 0x000C;
            IntPtr hwnd = FindWindow(null, "无标题 - 记事本");
            IntPtr htextbox = FindWindowEx(hwnd, IntPtr.Zero, "EDIT", null);
            IntPtr htextbox2 = FindWindowEx(hwnd, htextbox, "EDIT", null);//填上次获得的句柄,可以得到下一个的句柄。
            SendMessage(htextbox, WM_SETTEXT, IntPtr.Zero, this.txtText.Text);
        }

        //按下快捷键时被调用的方法
        public void CallBack()
        {
            Test();
        }using System;
using System.Windows.Forms;
u



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: