WPF 進程間通訊----inter-process communication


 

進程間通訊--inter-process communication 

 

進程間相互通訊的方法有很多,如用web services,xml 等互相讀取, 網絡的可以使用socket 等.


2個WinForm程序相互通訊可以使用重寫WndProc的方法,而WPF則不能。

先看如圖效果:

首先新建一個空白解決方案IPC

新建一個WPF項目命名為AppA

我們只需要點擊AppA中的button后AppB會提示已經點擊即可,
項目A的窗體XAML代碼:

<Window x:Class="IPC.AppA.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="App A" Height="350" Width="525">
    <Grid>
        <Button Name="btnOK" Content="Button" HorizontalAlignment="Left" Margin="202,135,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>
</Window>

  

項目A的后置代碼:

    public partial class MainWindow : Window
    {


        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern bool PostMessage(int hhwnd, uint msg, IntPtr wparam,
        IntPtr lparam);
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint RegisterWindowMessage(string lpString);
        private string msgstr = "inter-process communtcation";
        private uint msg;
        private const int HWND_BROADCAST = 0xffff;

        public MainWindow()
        {
            InitializeComponent();
            this.btnOK.Click += (s, e) => {
                this.Dispatcher.Invoke(delegate
                {
                    PostMessages();
                });
            };
        }

        protected void PostMessages()
        {
            msg = RegisterWindowMessage(msgstr);
            if (msg == 0)
            {
                MessageBox.Show(Marshal.GetLastWin32Error().ToString());
            }
            PostMessage(HWND_BROADCAST, msg, IntPtr.Zero, IntPtr.Zero);
        }

 

如下是項目B的窗體代碼:

<Window x:Class="IPC.AppB.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="App B" 
        Height="350"
        Width="525">
    <Grid>
        <Button Name="btnOK" Content="0" HorizontalAlignment="Left" Margin="230,132,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>
</Window>

  

項目B的后置代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace IPC.AppB
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private MainWindow _instance;
        private object _lock = new object();
        private string msgtext = "inter-process communtcation";
        private uint msg;
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint RegisterWindowMessage(string lpString);

        public MainWindow()
        {
            InitializeComponent();

            this.Loaded += (s, e) => {
                Load();
            };

            //this.btnOK.Click += (s, e) => {
            //    MessageBox.Show("AppB's button is clicked.");
            //};
        }

        public MainWindow Instance
        {
            get
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new MainWindow();
                    }
                    return _instance;
                }
            }
        }

        protected void Load()
        {
            MainWindow main = Instance;
            main.Dispatcher.Invoke(delegate {
                msg = RegisterWindowMessage(msgtext);
                if (msg == 0)
                {
                    MessageBox.Show(Marshal.GetLastWin32Error().ToString());
                }
            });
        }

        int i = 0;
        protected void PromptMsgs()
        {
            this.Dispatcher.Invoke(new Action(delegate
            {
                btnOK.Click += (s, e) =>
                {
                    //do nothing..
                };

                this.btnOK.Content = (++i).ToString();

                MessageBox.Show("AppB's button is clicked.");
            }));
        }


        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);

            HwndSource sorce = PresentationSource.FromVisual(this) as HwndSource;
            sorce.AddHook(new HwndSourceHook(WndProc));
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == this.msg)
            {
                PromptMsgs();
            }
            return IntPtr.Zero;
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            base.OnClosing(e);
            Environment.Exit(0);
        }
    }
}

 

 

需要代碼的朋友請留言!

源碼

 


免責聲明!

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



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