前言
在此之前对进程通信不太了解。
最近因项目需要稍有涉足,目前还在学习中。。。
正文
项目需求
两个独立的解决方案,属于两个项目,在系统中开辟两个进程。
需要在第一个项目中调用第二个项目,对第二个项目进行操作。
如:点击第一个项目的按钮,则触发第二个项目的按钮。
deom演示
针对项目需求,自己做了一个demo来进行尝试。
在这里分享给大家
程序截图
这里只对 被调用的程序 进行了截图, 调用窗体 只有一个button
被调用程序包括两个窗体,第一个窗体有一个button,点击显示 TestChild 子窗体
再次点击窗体 button “是” , 会有弹出框显示:是。
demo功能
点击第一个程序的按钮,之后会调用第二个程序(截图的程序)
连续自动点击两个按钮,最终显示提示框,内容为:是。
代码说明
首先为了使用API,添加引用命名空间
using System.Runtime.InteropServices;
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindowEx", SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, uint hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hwnd, uint wMsg, int wParam, int lParam);
[DllImport("user32.dll", EntryPoint = "SetForegroundWindow", SetLastError = true)]
private static extern void SetForegroundWindow(IntPtr hwnd);
思路:通过API,获取窗口句柄,根据窗口句柄给窗口发送消息,对窗体进行相应的操作
代码中对应各个的 标题 可以通过VS自带的spy++获取,下面有附有spy++的简单使用
private void button1_Click(object sender, EventArgs e)
{
const int WM_CLICK = 0x00F5;//鼠标点击消息,各种消息的数值,可以参考MSDN
string lpszName_Test = "Test";//主窗体的标题
string lpszName_btnShow = "显示子窗体";//主窗体上button的标题
string lpszName_TestChild = "TestChild";//子窗体的标题
string lpszName_btnYes = "是";//子窗体上button的标题
IntPtr hwndTest = new IntPtr();//主窗体的句柄
IntPtr hwndbtnShow = new IntPtr();//主窗体上button的句柄
IntPtr hwndTestChild = new IntPtr();//子窗体的句柄
IntPtr hwndbtnYes = new IntPtr();//子窗体上button的句柄
hwndTest = FindWindow(null, lpszName_Test);//获取主窗体的句柄
hwndbtnShow = FindWindowEx(hwndTest, 0, null, lpszName_btnShow);//获取主窗体上button的句柄
SetForegroundWindow(hwndTest);//使主窗体获得焦点
SendMessage(hwndbtnShow, WM_CLICK, 0, 0);//给主窗体上button发送鼠标点击消息,
hwndTestChild = FindWindow(null, lpszName_TestChild);//获取子窗体的句柄
hwndbtnYes = FindWindowEx(hwndTestChild, 0, null, lpszName_btnYes);//获取子窗体上button的句柄
SendMessage(hwndbtnYes, WM_CLICK, 0, 0);//给子窗体上button发送鼠标点击消息,
//逻辑判断并不严谨,这里只是展示一个简单的过程
}
spy++使用
首先运行程序
在“工具”中选择Spy++
从弹出的窗口中,选择 望远镜 的图片
再从弹出的窗口中,用鼠标选中 狙击镜的图标
用鼠标拖到你的目标窗体,则会显示“句柄”、“标题”、“类”三个数据
点击右上角“确定”按钮
在“窗口1”中会高亮显示你的目标窗体
右击选择属性
弹出窗口显示更多的窗体信息。
结语
笨~