目录
一、两种不同程序写的进程交互
1、定义交互消息
2、定义C++进程发来的消息ID
3、定义C++进程交互的句柄 及给C++进程发送的消息ID
4、定义交互消息所需的数据类型
5、引入所需的系统函数
6、给主进程发消息
7、写入本进程主窗口句柄
8、处理发来的交互消息
一、两种不同程序写的进程交互
1、定义交互消息
public const int WM_COPYDATA = 0x004A;public const int CSIDL_APPDATA = 0x001a;
2、定义C++进程发来的消息ID
public const int SubExe_EXIT = 1; //退出子进程public const int SubExe_Show = 2;public const int SubExe_Hide = 3;public const int SubExe_SendInfo = -1;
3、定义C++进程交互的句柄 及给C++进程发送的消息ID
public int m_hxnwHWND = 0;public const int ToXnwInfo = 200; //给C++进程发送
4、定义交互消息所需的数据类型
struct COPYDATASTRUCT{public IntPtr dwData; // Any value the sender chooses. Perhaps its main window handle?public int cbData; // The count of bytes in the message.public IntPtr lpData; // The address of the message.}public struct COPY_DATA{public IntPtr dwData;public int cbData;[MarshalAs(UnmanagedType.LPStr)]public string lpData;}
5、引入所需的系统函数
[DllImport("kernel32.dll")]static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName,string lpString, string lpPath);[DllImport("kernel32.dll")]private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);[DllImport("user32.dll")]public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);[DllImport("shell32.dll")]static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, uint dwFlags, [Out] StringBuilder pszPath);
6、给主进程发消息
public static void SendXnwMessage(int hWnd, string message){IntPtr lpData = Marshal.StringToHGlobalAnsi(message);COPYDATASTRUCT data = new COPYDATASTRUCT();data.dwData = (IntPtr)ToXnwInfo;data.cbData = message.Length + 1;data.lpData = lpData;IntPtr lpStruct = Marshal.AllocHGlobal(Marshal.SizeOf(data));Marshal.StructureToPtr(data, lpStruct, false);IntPtr nWp = IntPtr.Zero;SendMessage((IntPtr)hWnd, WM_COPYDATA, nWp, lpStruct);}
7、写入本进程主窗口句柄
public void WriteHwnd(IntPtr hwnd){const int MaxPath = 260;StringBuilder builder = new StringBuilder(MaxPath);SHGetFolderPath(IntPtr.Zero, (int)CSIDL_APPDATA, IntPtr.Zero, 0x0000, builder);string path = builder.ToString() + "\\kuaileketang";Directory.CreateDirectory(path);path += "\\hWnd.ini";string text = String.Format("{0}", hwnd);WritePrivateProfileString("Wnd", "hWnd", text, path);读取校内外窗口句柄StringBuilder temp = new StringBuilder(256);int i = GetPrivateProfileString("Wnd", "hParent", "0", temp, 256, path);string xnwHwndStr = temp.ToString();m_hxnwHWND = int.Parse(xnwHwndStr);if (true)SendXnwMessage(m_hxnwHWND, ""); //若有环境,则发送空信息elseSendXnwMessage(m_hxnwHWND, "www.biying.com"); //若没有环境,则发送下载该环境所需的网址 }
8、处理发来的交互消息
public void onCopyData(int msg, IntPtr wParam, IntPtr lParam){if (msg == WM_COPYDATA){COPY_DATA copyData = (COPY_DATA)Marshal.PtrToStructure(lParam, typeof(COPY_DATA));if (null != copyData.lpData){int id = (int)copyData.dwData;string jstr = copyData.lpData;switch(id){case SubExe_EXIT:{UnsetHotkey();trayIcon.Dispose();Application.Exit();}break;}}}}