devilhand 发表于 2013-2-7 04:25:06

向另一个程序中的文本框发送消息

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;namespace SendFormMessage{    public partial class Form1 : Form    {      private IntPtr hwnd_win ;      private IntPtr hwnd_button ;      private IntPtr hwnd_text ;      const int WM_SETTEXT = 0x000C;//文本类型参数      const int BM_CLICK = 0x00F5;//单击参数         //查找窗体句柄            public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);      //查找子窗体句柄(包括按钮、文本框等)            public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);      //发送消息(把消息放入消息队列中)            public static extern IntPtr PostMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);      //设置窗体的标题            public static extern bool SetWindowText(IntPtr hwnd, string lpString);      //发送消息(要等处理程序处理完,发送程序才能继续执行)            public static extern int SendTextMessage(IntPtr hWnd, int Msg, int wParam, string lParam);      public Form1()      {            InitializeComponent();      }      private void Form1_Load(object sender, EventArgs e)      {            hwnd_win = FindWindow(null, "登录");//窗口的名称,获取窗口句柄             hwnd_button = FindWindowEx(hwnd_win, new IntPtr(0), null, "点击");//获取确定按钮的句柄            hwnd_text = FindWindowEx(hwnd_win, IntPtr.Zero, "WindowsForms10.EDIT.app.0.378734a", null);//获取密码框的句柄,通过SPY++软件获得文本框的类名 "WindowsForms10.EDIT.app.0.378734a"         }      private void SendMessage_Click(object sender, EventArgs e)      {            //SetWindowText(hwnd_button, "窗体标题");//设置窗体标题            SendTextMessage(hwnd_text, WM_SETTEXT, 0, "这是从另一个程序传过的消息");//向文本框中发送信息             SendTextMessage(hwnd_button, BM_CLICK, 0, "");//向文本框中发送信息                  }      private void PostMessages_Click(object sender, EventArgs e)      {            SendTextMessage(hwnd_text, WM_SETTEXT, 0, "这是从另一个程序传过的消息");//向文本框中发送信息             Message msg = Message.Create(hwnd_button, BM_CLICK, new IntPtr(0), new IntPtr(0));//创建单击按钮消息            PostMessage(msg.HWnd, msg.Msg, msg.WParam, msg.LParam);//发送单击按钮的消息      }    }} 注:SendTextMessage和PostMessage区别:前者把钩子截获的消息发送到主处理程序进行处理,在主处理程序没有处理完前,被设置钩子的程序处于停止状态。即要等到其它程序处理完返回后,才继续执行。后者只是把消息放入队列,不管其它程序是否处理都返回,然后继续执行。
页: [1]
查看完整版本: 向另一个程序中的文本框发送消息