快捷搜索:  as  2018  FtCWSyGV  С˵  test  xxx  Ψһ  w3viyKQx

澳门新葡亰集团_龟发之家论坛



在实际项目利用中,常常会必要本机中不合的进程互相直接必要通信。

范例利用处景:

剪切板在不合利用法度榜样间操作。

节制法度榜样给予第三要领度榜样通信节制接口,如播放器节制开关等。

在Windows操作系统中,进程间互相通信的要领至少可以列5种以上,本文讲述在WPF情况下对照简便的办理规划:

1.WCF NetNamedPipeBinding

2.Win32

1.WCF NetNamedPipeBinding

NetNamedPipeBinding适用于本机间进程通信,基于命名管道来进行消息通报。

Link:http://msdn.microsoft.com/zh-cn/library/ms752247.aspx

引用System.ServiceModel,定义一组端对真个通信接口:

namespace IPCInterface

{[ServiceCon澳门新葡亰集团tract(SessionMode = SessionMode.Allowed)]

public interface IC2SMessages {[OperationContract(IsOneWay = true)]

void Register(Guid clientID);

[OperationContract(IsOneWay = true)]void DisplayCommandOnServer(string text);

}}

namespace IPCInterface {

[ServiceContract(SessionMode = SessionMode.Allowed)]public interface IS2CMessages {

[OperationContract(IsOneWay = true)]void CommandInClient(string text);

}}

在发送端实现:

namespace WinTarget {

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant, InstanceContextMode = InstanceContextMode.Single)]public partial class MainWindow : Window, IC2SMessages {

ServiceHost _serverHost;List _registeredClients = new List();

public MainWindow() {

InitializeComponent();

_serverHost = new ServiceHost(this);

_serverHost.AddServiceEndpoint((typeof(IC2SMessages)), new NetNamedPi澳门新葡亰集团peBinding(), "net.pipe://localhost/Server");_serverHost.Open();

}

private void SendText(Guid client, string text) {using (ChannelFactory factory = new ChannelFactory(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/Client_" + client.ToString()))) {

IS2CMessages serverToClientChannel = factory.CreateChannel();try {

serverToClientChannel.CommandInClient(text);} catch (Exception ex) {

MessageBox.Show(ex.ToString());} finally {

CloseChannel((ICommunicationObject)serverToClientChannel);}

}}

private void CloseChannel(ICommunicationObject channel) {

try {channel.Close();

} catch (Exception ex) {MessageBox.Show(ex.ToString());

} finally {channel.Abort();

}}

public void Register(Guid clientID) {

if (!_registeredClients.Contains(clientID)) {_registeredClients.Add(clientID);

}}

public void DisplayCommandOnServer(string text) {

lbmessage.Content = text;}

private void Play_Click(object sender, RoutedEventArgs e) {

foreach (Guid client in _registeredClients) {SendText(client, "Play");

}}

private void Pause_Click(object sender, RoutedEventArgs e) {

foreach (Guid client in _registeredClients) {SendText(client, "Pause");

}}

}}

吸收端实现:

namespace WinSource {

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant, InstanceContextMode = InstanceContextMode.Single)]public partial class MainWindow : Window, IS2CMessages {

Guid _clientID;ServiceHost _clientHost;

public MainWindow() {

InitializeComponent();

_clientID = Guid.NewGuid();_clientHost = new ServiceHost(this);

_clientHost.AddServiceEndpoint((typeof(IS2CMessages)), new NetNamedPipeBinding(), "net.pipe://localhost/Client_" + _clientID.ToString澳门新葡亰集团());

_clientHost.Open();

this.Loaded += OnLoaded;}

void OnLoaded(object sender, RoutedEventArgs e) {

this.Dispatcher.BeginInvoke(new Action(() => {Register(_clientID);

}));

media.LoadedBehavior = MediaSta澳门新葡亰集团te.Manual;media.Source = new Uri(@"D:\Test\IMG_0245.MOV");

media.Play();}

public void Register(Guid clientID) {using (ChannelFactory factory = new ChannelFactory(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/Server"))) {

IC2SMessages clientToServerChannel = factory.CreateChannel();try {

clientToServerChannel.Register(clientID);clientToServerChannel.DisplayCommandOnServer(string.Format("+Client:{0}", clientID.ToString()));

} catch (Exception ex) {MessageBox.Show(ex.ToString());

} finally {CloseChannel((ICommunicationObject)clientToServerChannel);

}}

}

private void CloseChannel(ICommunicationObject channel) {try {

channel.Close();} catch (Exception ex) {

MessageBox.Show(ex.ToString());} finally {

channel.Abort();}

}

public void CommandInClient(string text) {if (text == "Play") {

media.Play();} else {

media.Pause();}

}}

}

履行效果:

2.Win32

发送端引用 User32.dll SendMessage和FindWindow

MessageHelper类:

public class MessageHelper {

public const int WM_COPYDATA = 0x004A;

[DllImport("User32.dll", EntryPoint = "SendMessage")]private static extern int SendMessage

(IntPtr hWnd,//目标窗体句柄

int Msg,//WM_COPYDATAint wParam,//自定义数值

refCopyDataStruct lParam//布局体);

[DllImport("User32.dll", EntryPoint = "FindWindow")]

pu澳门新葡亰集团blic static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

public static void SendMessage(string windowName, string strMsg) {

if (strMsg == null) return;

IntPtr hwnd = FindWindow(null, windowName);

if (hwnd != IntPtr.Zero) {CopyDataStruct cds;

cds.dwData = IntPtr.Zero;

cds.lpData = strMsg;

cds.cbData = System.Text.Encoding.Default.GetBytes(strMsg).Length + 1;

int fromWindowHandler = 0;SendMessage(hwnd, WM_COPYDATA, fromWindowHandler, refcds);

}}

public static void SendMessageByProcess(string processName, string strMsg) {

if (strMsg == null) return;var process = Process.GetProcessesByName(processName);

if (process.FirstOrDefault() == null) return;var hwnd = process.FirstOrDefault().MainWindowHandle;

if (hwnd == IntPtr.Zero) return;

if (hwnd != IntPtr.Zero) {CopyDataStruct cds;

cds.dwData = IntPtr.Zero;

cds.lpData = strMsg;

cds.cbData = System.Text.Encoding.Default.GetBytes(strMsg).Length + 1;

int fromWindowHandler = 0;SendMessage(hwnd, WM_COPYDATA, fromWindowHandler, refcds);

}

}

[StructLayout(LayoutKind.Sequential)]public struct CopyDataStruct {

public IntPtr dwData;public int cbData;

[MarshalAs(UnmanagedType.LPStr)]

public string lpData;}

}

发送端发送消息:

MessageHelper.SendMessageByProcess("WinSource", "Play");

MessageHelper.SendMessageByProcess("WinSource", "Pause");

吸收端MessageHelper类

public class MessageHelper {

public const int WM_COPYDATA = 0x004A;}

[StructLayout(LayoutKind.Sequential)]public struct CopyDataStruct {

public IntPtr dwData;

public int cbData;//字符串长度

[MarshalAs(UnmanagedType.LPStr)]

public string lpData;//字符串}

吸收端吸收另一进程消息,并做处置惩罚动作

void MainWindow_Loaded(object sender, RoutedEventArgs e) {

(PresentationSource.FromVisual(this) as HwndSource).AddHook(new HwndSourceHook(this.WndProc));if (Application.Current.Properties["ArbitraryArgName"] != null) {

try {string fname = Application.Current.Properties["ArbitraryArgName"].ToString();

midea.Source = new Uri(fname);midea.Play();

Status = true;} catch (Exception ex) {

MessageBox.Show(ex.ToString());}

}

}

IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) {

if (msg == MessageHelper.WM_COPYDATA) {CopyDataStruct cds = (CopyDataStruct)System.Runtime.InteropServices.Marshal.PtrToStructure(lParam, typeof(CopyDataStruct));

if (cds.lpData == "Play") {if (Status) {

midea.Pause();Status = false;

} else {midea.Play();

Status = true;}

}}

return hwnd;}

这样达到的效果和应用WCF NamedPipeBinding效果是一样的。

代码戳:ProcessCommunication.7z

转自:http://www.cnblogs.com/tmywu/archive/2013/05/09/3069279.html

您可能还会对下面的文章感兴趣: