2013-04-05 79 views
0

我有我已經註冊爲URI方案一個WPF應用程序通過執行以下操作。註冊申請URI方案

HKEY_CLASSES_ROOT 
-->myappname 
    -->shell 
     -->open 
     -->command 
      (Default) = "c:\pathtomyapp\app.exe" 

太棒了!但是,我的應用程序強制一次只能運行一個實例。我如何檢測到我的應用程序已在運行,例如將其展示在前臺?

+0

敬請展示如何您通過URI方案執行APP.EXE? – YumYumYum 2014-06-30 06:56:43

+1

請考慮修改此問題的標題。它更多的是處理單個實例而不是URI方案處理程序。 – 2015-02-11 10:17:36

回答

2

您可以使用一個名爲互斥體檢測到應用程序已經運行。或者,如果你有一個GUI應用程序,你可以從VisualBasic's SingleInstance application繼承的形式,它會爲你做routhgly相同。

public class SingleInstanceController 
    : WindowsFormsApplicationBase 
    { 
    public SingleInstanceController() 
    { 
     // Set whether the application is single instance 
     this.IsSingleInstance = true; 

     this.StartupNextInstance += new 
     StartupNextInstanceEventHandler(this_StartupNextInstance); 
    } 

    void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e) 
    { 
     // Here you get the control when any other instance is 
     // invoked apart from the first one. 
     // You have args here in e.CommandLine. 

     // You custom code which should be run on other instances 
    } 

    protected override void OnCreateMainForm() 
    { 
     // Instantiate your main application form 
     this.MainForm = new Form1(); 
    } 
    } 

[STAThread] 
static void Main(string[] args) 
{  
    SingleInstanceController controller = new SingleInstanceController(); 
    controller.Run(args); 
} 

,只要您在C#編寫代碼,因爲這個類是avaliable作爲.NET框架的一個組成部分,所有的語言沒關係。

這裏是一個wrapper for the WPF

+0

這東西好像被綁定到'WindowsForms'。這是適合在WPF應用程序中使用嗎? – Julien 2013-04-05 19:31:17

+0

添加wpf包裝鏈接到答案。 – alex 2013-04-05 19:36:14

+0

這幾乎是完美的。不幸的是,使用.NET 4.0時WPF包裝器錯誤 – Julien 2013-04-08 16:32:24