接收端代码:
[StructLayout(LayoutKind.Sequential)] public struct CopyDataStruc { public IntPtr dwData; public int cbData; // 字符串长度 [MarshalAs(UnmanagedType.LPStr)] public string lpData; // 字符串 } private void Window_Loaded(object sender, RoutedEventArgs e) { (PresentationSource.FromVisual(this) as HwndSource).AddHook(new HwndSourceHook(this.WndProc)); } IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == MessageHelper.WM_DOWNLOAD_COMPLETED) { //CopyDataStruct cds = (CopyDataStruct)System.Runtime.InteropServices.Marshal.PtrToStructure(lParam, typeof(CopyDataStruct)); MessageBox.Show("I got it!"); } return hwnd; }
发送端代码:
private void PostMessage() { Process proc = Process.GetProcessesByName("MyAppSample")[0]; //Process[] procs = Process.GetProcesses(); //foreach (Process p in procs) //{ // if (p.ProcessName == "MyAppSample") // { // proc = p; // } //} IntPtr hwnd = MessageHelper.FindWindow(null, "MainWindow"); MessageHelper.PostMessage(hwnd, MessageHelper.WM_DOWNLOAD_COMPLETED, IntPtr.Zero, IntPtr.Zero); MessageHelper.PostMessage(proc.MainWindowHandle, MessageHelper.WM_DOWNLOAD_COMPLETED, IntPtr.Zero, IntPtr.Zero); } public class MessageHelper { public const int WM_DOWNLOAD_COMPLETED = 0x00AA; [DllImport("User32.dll", EntryPoint = "FindWindow")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("User32.dll", EntryPoint = "SendMessage")] public static extern int SendMessage(IntPtr wnd, int msg, IntPtr wP, IntPtr lP); //private static extern int SendMessage //( // IntPtr hWnd, //目标窗体句柄 // int Msg, //WM_COPYDATA // int wParam, //自定义数值 // ref CopyDataStruct lParam //结构体 //); [DllImport("User32.dll", EntryPoint = "PostMessage")] public static extern int PostMessage(IntPtr wnd, int msg, IntPtr wP, IntPtr lP);