问题描述:

How to check programmatically whether my WPF app is working or not right now?, Like App.PrevInstance in VB.

Please suggest me a simple method, i am beginner.

Here my code,

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);

}

It is always showing Application is already Running :P

网友答案:

What most people do is use a named Mutex object. Use the constructor overload that tells you if it was successfully created to find out if another process has already created one with the same name. Example for using the mutex:

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");
 }

You can also read this How to determine if a previous instance of my application is running?

网友答案:

You can check process name as specified in the link I gave in the comment:

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);
    }
}
相关阅读:
Top