2017-05-29 214 views
-1

基本上我们假设我有一个C#MP3播放器正在运行,并且我想要更改歌曲或只是从命令行调用某个函数。从另一个C#应用程序调用C#应用程序的方法

假设MP3播放器名为mp3.exe,我想在应用程序本身仍在运行时从应用程序外部更改歌曲。所以我在想,创建一个名为mp3call.exe另一个应用程序,这样我就可以运行,那么

mp3call -play "<song_here>" 

mp3call.exe将从调用MP3内的一些方法Play,像Play(<song_here>)

这是否易于管理?如果是这样,怎么样?

+0

https://msdn.microsoft.com/en-us/library/aa730857(v=vs.80).aspx –

+0

hmmm您可以将参数传递给应用程序,使用某种机制在两个应用程序之间构建消息传递,公开从应用程序的API作为共享库,... – niceman

+0

@HansPassant你的链接是旧的 – niceman

回答

-1

我已经研究了一些关于这个话题,因为它似乎很有趣。我想你可以通过使用Win32来做到这一点。我做了一个非常非常简单的示例。两个WPF应用程序,第一个名为WpfSender,第二个名为WpfListener。 WpfSender会发送一条消息给WpfListener进程。

WpfSender只有一个按钮,一旦它被点击就发送消息。 WpfListener只是一个空的窗口,当从WpfSender收到消息时将显示一个消息框。

enter image description here

下面是代码背后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

希望这有助于!

+0

当投票否定时,请留下评论,以便我们改进我们的答案 – taquion

相关问题