First, we install the desktop application on our computer. After successful installation, there will be a shortcut icon on the desktop, as shown in the below figure.
We can open the application multiple times with multiple clicks on that icon. You can look at the below figure.
For preventing or the application from opening multiple times, we need to write the following codes. Please write this code in Program.cs.
Program.cs
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using DomainEntities;
- using System.Xml;
- using CCMS.Forms;
- using System.Threading;
- namespace CCMS {
- static class Program {
-
-
-
- [STAThread]
- static void Main() {
- try {
- const string APPGUID = "{9F6F0AC4-B9A1-90AB-DE0F-72F04E6BDE8F}";
- using(Mutex mutex = new Mutex(false, APPGUID)) {
- if (!mutex.WaitOne(0, false)) {
- MessageBox.Show("Already Running Application!", "An instance of the application is already running...", MessageBoxButtons.OK, MessageBoxIcon.Stop);
- return;
- }
- Application.Run(new LoginPage());
- }
- } catch (Exception ex) {
- MessageBox.Show(ex.Message.ToString(), "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
- }
- }
You can replace APPGUID with your own.
We will get this type of warning after trying to open the application multiple times if it is already opened.
Conclusion
We learned how to prevent an application from opening multiple times if an instance of the application is already opened. Thank you.