Checking if an application is already running

Many Windows Forms applications only allow a single instance to run at a time. The following snippet is a clean way to check if your process is already running:

static public bool AlreadyRunning()
{
    string processName = Process.GetCurrentProcess().ProcessName;
    Process[] processes = Process.GetProcessesByName(processName);
    return (processes.Length > 1);
}

6 Comments

  • No it isn't. There can be other process with the same name, since the name doesn't include the executable's path (or extension). You can check the Process.MainModule of processes by the same name to see if it's really your process. And does GetProcessesByName return processes that are running under a different user? If yes then do you really want to allow only one user to run your process at a time?

  • Not to mention that the other program called "myprog.exe" might not be a copy of you. It might just happen to have the same name by coincidence.



    Try it: Rename your program to "explorer.exe" and run it - oops, it thinks it's already running.

  • Raymond - isn't that what I've said? The only way to know for sure is to find the main module path and compare it to the full path of the main module of the process doing the check - and not just a string comparison, the same path can be expressed at least four ways, C:\Path\process.exe, \\.\C$\Path\process.exe, \\?\C:\Path\process.exe and \\?.\C$\Path\process.exe all point to the same file. And of course there's still the issue of security contexts (which may not be an issue if GetProcessesByName only returns processes for the current user).

  • Not Working!!!!!!!!!

  • Even to find out that one process is running with a name the same as the current name I think it should be processes.Length >= 1

  • thanks man.. works perfectly.. :)

Comments have been disabled for this content.