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.
- public sealed class SingleInstance
- {
- public static bool AlreadyRunning()
- {
- bool running = false;
- try
- {
-
- Process currentProcess = Process.GetCurrentProcess();
-
-
- foreach (var p in Process.GetProcesses())
- {
- if (p.Id != currentProcess.Id)
- {
- if (p.ProcessName.Equals(currentProcess.ProcessName) == true)
- {
- running = true;
- IntPtr hFound = p.MainWindowHandle;
- if (User32API.IsIconic(hFound))
- User32API.ShowWindow(hFound, User32API.SW_RESTORE);
- User32API.SetForegroundWindow(hFound);
- break;
- }
- }
- }
- }
- catch { }
- return running;
- }
NOTE
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.
- using System.Runtime.InteropServices;
- public class User32API
- {
- [DllImport("User32.dll")]
- public static extern bool IsIconic(IntPtr hWnd);
-
- [DllImport("User32.dll")]
- public static extern bool SetForegroundWindow(IntPtr hWnd);
-
- [DllImport("User32.dll")]
- public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
-
- public const int SW_RESTORE = 9;
- }
Step 3 Implement this in our application.
In WPF
Open App.xaml.cs (under App.xaml) from the Solution Explorer and overriding the OnStartup method.
- protected override void OnStartup(StartupEventArgs e)
- {
- if (SingleInstance.AlreadyRunning())
- App.Current.Shutdown();
-
- base.OnStartup(e);
- }
In Windows Form
Open Program.cs from Solution Explorer and modify the snippet.
- static class Program
- {
-
-
-
- [STAThread]
- static void Main()
- {
- Application.EnableVisualStyles();
- Application.SetCompatibleTextRenderingDefault(false);
-
-
- if(!SingleInstance.AlreadyRunning())
- Application.Run(new Form1());
- }
- }
Conclusion
Implementing two classes in our Application restricts the user to allowing multiple instances.
I hope, you enjoyed reading this blog. Stay connected to C# Corner for more updates.