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);
}
Published 28 May 2004 11:11 AM by Ted_Graham
Filed under:

Comments

# Jerry Pisk said on 28 May, 2004 03:02 PM
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?
# Raymond Chen said on 28 May, 2004 10:05 PM
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.
# Jerry Pisk said on 29 May, 2004 03:55 PM
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).
# TrackBack said on 10 April, 2005 09:08 AM
^_^,Pretty Good!
# Ali Adnan said on 02 July, 2008 03:01 AM

Not Working!!!!!!!!!

# Noel Wood said on 10 September, 2008 01:51 AM

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

# Suganya said on 18 November, 2008 05:07 PM

This code snippet doesnt work.

# Olgunka-gj said on 26 December, 2008 07:43 AM

<a href= membres.lycos.fr/maffals >genetic disorters</a>

# elexx-nz said on 26 December, 2008 07:47 AM

<a href= membres.lycos.fr/dertull >zx10r graphics</a>

# camilord said on 24 February, 2009 11:27 AM

thanks man.. works perfectly.. :)

# Olgunka-lc said on 01 March, 2009 12:02 AM

<a href= http://adultromancefinder.com >find partner</a>

# elexx-wk said on 01 March, 2009 12:03 AM

<a href= adultpersonalsfinder.com >find partner</a>

# weblogs.asp.net said on 15 May, 2011 01:41 PM

143907.. Retweeted it :)

# weblogs.asp.net said on 30 June, 2011 12:41 AM

143907.. Corking :)

Leave a Comment

(required) 
(required) 
(optional)
(required)