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

 

 

需要代码的朋友请留言!

源码

 

posted @ 2013-10-14 17:38  风清扬 No.1  阅读(2825)  评论(15编辑  收藏  举报