WPF通過消息機制實現進程間通信(IPC)


接收端代碼:

[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);
        

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM