2015-06-03 350 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

仔细检查一下,双重过程同名吗? –

相关问题