我对该主题进行了一些研究,因为它看起来很有趣。我认为你可以通过使用 Win32 来做到这一点。我做了一个非常简单的示例。两个 WPF 应用程序,第一个名为 WpfSender,第二个名为 WpfListener。 WpfSender 将向 WpfListener 进程发送消息。
WpfSender 只有一个按钮,点击后发送消息。 WpfListener 只是一个空窗口,当接收到来自 WpfSender 的消息时会显示一个消息框。
这是 WpfSender 背后的代码
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
namespace WpfSender
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var process = Process.GetProcessesByName("WpfListener").FirstOrDefault();
if (process == null)
{
MessageBox.Show("Listener not running");
}
else
{
SendMessage(process.MainWindowHandle, RF_TESTMESSAGE, IntPtr.Zero, IntPtr.Zero);
}
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SendMessage(IntPtr hwnd, uint Msg, IntPtr wParam, IntPtr lParam);
private const int RF_TESTMESSAGE = 0xA123;
}
}
您使用 Win32 api 跨 Windows 应用程序发送消息
这是 WpfListener 的代码
using System;
using System.Windows;
using System.Windows.Interop;
namespace WpfListener
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
source.AddHook(WndProc);
}
private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == RF_TESTMESSAGE)
{
MessageBox.Show("I receive a msg here a I can call the method");
handled = true;
}
return IntPtr.Zero;
}
private const int RF_TESTMESSAGE = 0xA123;
}
}
我不在这里写 XAML,因为它非常简单。同样,这是一个非常简单的示例,向您展示如何实现跨应用程序消息发送。极限是你的想象力。您可以声明许多 int 常量,每个常量代表一个动作,然后在 switch 语句中您可以调用选定的动作。
我不得不说我关注了我在研究中发现的两篇文章:
For knowing how to handle WndProc in Wpf
For knowing how to send messages using win32 api
希望这会有所帮助!