2015-06-03 351 views
-2

如何以編程方式檢查我的WPF應用程序現在是否正在工作?,就像VB中的App.PrevInstance一樣。 請給我一個簡單的方法,我是初學者。檢查當前的WPF應用程序是否正在運行?

這裏我的代碼,

protected override void OnStartup(StartupEventArgs e) 
{ 
    base.OnStartup(e); 
    var runningProcessByName = Process.GetProcessesByName("TCLCGFP"); 
    if (runningProcessByName.Length == 0) 
    { 
     //Process.Start("TCLCGFP.exe"); 
     new TraacsClcProcess(); 
    } 
    else 
    { 
     MessageBox.Show("Application is already Running.","TCLCGFP",MessageBoxButton.OK,MessageBoxImage.Information); 
    } 
    Environment.Exit(0); 
} 

它總是顯示應用程序已經運行:P

+0

可能重複[檢查如果Windows應用程序運行](http://stackoverflow.com/questions/4722198/checking-if-windows-application-is-running) – demonplus

+0

我正在尋找簡單的代碼,如在VB中使用App.PrevInstance。 –

+0

然後更新您的問題與確切的細節,你需要什麼和你已經嘗試 – demonplus

回答

2

大多數人做的是使用一個名爲互斥對象。使用構造函數重載,告訴您它是否已成功創建,以確定另一個進程是否已創建具有相同名稱的進程。例如使用互斥:

Mutex mutex; 

try 
{ 
    mutex = Mutex.OpenExisting("SINGLEINSTANCE"); 

    if (mutex!= null) 
    { 
     Console.WriteLine("Error, 1 instance Only"); 
     Application.Exit(); 
    } 
} 
catch (WaitHandleCannotBeOpenedException ex) 
{ 
     mutex = new Mutex(true, "SINGLEINSTANCE"); 
} 

你也可以閱讀How to determine if a previous instance of my application is running?

+0

我沒有得到你的代碼人.. 我如何實現你的代碼到我的應用程序。 –

0

在我的意見給了鏈接指定您可以查看進程名稱:中

public partial class App : System.Windows.Application 
{ 
    public bool IsProcessOpen(string name) 
    { 
     foreach (Process clsProcess in Process.GetProcesses()) { 
      if (clsProcess.ProcessName.Contains(name)) 
      { 
       return true; 
      } 
     } 
     return false; 
    } 

protected override void OnStartup(StartupEventArgs e) 
{ 
    // Get Reference to the current Process 
    Process thisProc = Process.GetCurrentProcess(); 
    if (IsProcessOpen("TCLCGFP.exe") == false) 
    { 
     //System.Windows.MessageBox.Show("Application not open!"); 
     //System.Windows.Application.Current.Shutdown(); 
    } 
    else 
    { 
     // Check how many total processes have the same name as the current one 
     if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1) 
     { 
      // If ther is more than one, than it is already running. 
      System.Windows.MessageBox.Show("Application is already running."); 
      System.Windows.Application.Current.Shutdown(); 
      return; 
     } 
     base.OnStartup(e); 
    } 
} 
+0

....它始終顯示「應用程序未打開」。當代碼 - > IsProcessOpen(「TraacsCLCGalileoFocalPoint.exe」)。 和「應用程序已經運行」當我刪除「.exe」 像 - > IsProcessOpen(「TraacsCLCGalileoFocalPoint」)。 –

+0

請問您可以使用Process Manager仔細檢查流程名稱嗎? – demonplus

+0

仔細檢查一下,雙重過程同名嗎? –

相關問題