In some cases, we might have to run only a single instance of our application and restrict a user to running multiple instances of the application at a time (for example. Windows Media Player). This blog is applicable to both Windows Form and WPF Applications.
Getting Started
Step 1
Create a class file named SingleInstance.cs in your project.
Create a class file named SingleInstance.cs in your project.
- public sealed class SingleInstance
- {
- public static bool AlreadyRunning()
- {
- bool running = false;
- try
- {
- // Getting collection of process
- Process currentProcess = Process.GetCurrentProcess();
- // Check with other process already running
- foreach (var p in Process.GetProcesses())
- {
- if (p.Id != currentProcess.Id) // Check running process
- {
- if (p.ProcessName.Equals(currentProcess.ProcessName) == true)
- {
- running = true;
- IntPtr hFound = p.MainWindowHandle;
- if (User32API.IsIconic(hFound)) // If application is in ICONIC mode then
- User32API.ShowWindow(hFound, User32API.SW_RESTORE);
- User32API.SetForegroundWindow(hFound); // Activate the window, if process is already running
- break;
- }
- }
- }
- }
- catch { }
- return running;
- }
SingleInstance class has been declared sealed to avoid memory leakage.
To set the running process to the foreground, we have to use the functions availabe in User32.dll
We are creating another class i.e. UserAPI class.
Step2
Create a class file named User32API.cs.
We are creating another class i.e. UserAPI class.
Step2
Create a class file named User32API.cs.

Ravi SinghPosted May 25, 2020, 6:54 AM
Thanks Bro....
Former memberPosted May 17, 2017, 10:15 AM
Are you trying to say SO code is not working?
Former memberPosted May 17, 2017, 5:49 AM
You can use Mutex class instead of iterate in process list. here is one link http://stackoverflow.com/a/819808/6188148
Manas MohapatraPosted May 17, 2017, 2:41 AM
Good one to know about single instance of app run..