2017-05-29 114 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

相關問題