说来说去,还是觉得API的功能是最强大的,但是.NET FCL,MFC等对API的封装之后也使得程序的开发变得更加容易。本模块的主要原理还是使用API,查找指定类型,窗口文本的窗口对象,使用C#发送消息,获取该对象的指针。然后实现C#应用程序间使用C#发送消息操作该对象。
C#发送消息实例1:
创建一个C#Windows Form应用程序,向窗口中添加一个按钮button1,添加事件相应函数:
private void button1_Click(object sender, System.EventArgs e)
{
MessageBox.Show("This is button1 click!");
}
- 1.
- 2.
- 3.
- 4.
C#发送消息实例2:
创建一个C# Windows Form应用程序,添加一个按钮控件button1
1:C#在应用程序添加using System.Runtime.InteropServices;
2:C#在应用程序添加对API的引用:
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent,IntPtr hwndChildAfter,string lpszClass,string lpszWindow);
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
public static extern IntPtr PostMessage(IntPtr hwnd,int wMsg,IntPtr wParam,IntPtr lParam);
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
3:C#在应用程序添加button1的相应函数:
private void button1_Click(object sender, System.EventArgs e)
{
IntPtr hwnd_win ; // 存放实例1中的Form1窗口的窗口句柄
IntPtr hwnd_button ; // 存放实例1中的Form1中的button1控件的窗口句柄
// 参数1:窗口类型,参数2:窗口名称
hwnd_win = FindWindow("WindowsForms10.Window.8.app3", "Form1"); // 得到Form1窗口的句柄。
// 参数1:父窗口句柄, 参数2:子窗口指针;参数3:窗口类型;参数4:窗口文本
hwnd_button = FindWindowEx(hwnd_win ,new IntPtr(0) ,"WindowsForms10.BUTTON.app3","button1");
// 定义待发送的消息
const int BM_CLICK = 0x00F5;
Message msg = Message.Create(hwnd_button ,BM_CLICK ,new IntPtr(0),new IntPtr(0));
// 向Form1窗口的button1控件发送BM_CLICK消息
PostMessage(msg.HWnd ,msg.Msg ,msg.WParam ,msg.LParam);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
总结:
其实C#幕后还是采用的C#发送消息的处理机制,本创许也充分利用了Windows的消息处理机之。
附带一个获取窗口类型的技巧:使用SPY ++就可以获取任何窗口的窗口类型。
所有的类似于WM_CHAR,WM_COMMAND等消息的值,可以在.Net目录下的WinUser.h文件中查询到。
【编辑推荐】