I've a C# application that displays a login form when launched and displays the main form after users are authenticated. I used Mutex to restrict that only one instance of my application runs. And, this works fine for only the Login form. Once the main form is displayed, it doesn't restrict users from reopening the Login form. I was looking for a solution by which the Login screen couldn't be displayed once the main form is already opened.
Here is my Program.cs
[STAThread]
static void Main()
{
bool mutexCreated=true;
using (Mutex mutex = new Mutex(true, "eCS", out mutexCreated))
{
if (mutexCreated)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
XtraMessageBox.Show("Another instance of eCS is already running.", "eCS already running", MessageBoxButtons.OK, MessageBoxIcon.Information);
SetForegroundWindow(process.MainWindowHandle);
break;
}
}
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…