所以这段代码在 program.cs 中,应该检查连接是否可用以及是否有另一个实例已经在运行。如果有,消息框会通知用户,并询问他是否确定要打开应用程序。接下来是问题:我打开应用程序,然后再次打开它,消息框显示但没有任何反应。我重复这些过程,仅在 4-5 次后才有效。然后,如果我再次打开,它会打开 2 个实例。
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SqlConnection con123 = new SqlConnection(con123.Metoda());
Mutex mut = null;
try
{
mut = Mutex.OpenExisting("Tray minimizer");
}
catch
{
}
if (mut == null)
{
mut = new Mutex(true, "Tray minimizer");
Application.Run(new Form1());
//Tell GC not to destroy mutex until the application is running and
//release the mutex when application exits.
GC.KeepAlive(mut);
mut.ReleaseMutex();
}
else
{
//The mutex existed so exit
mut.Close();
DialogResult result = MessageBox.Show("AApplication is already working!Do you want to reopen it?", "Caution!", MessageBoxButtons.OKCancel);
if (result == DialogResult.OK)
{
foreach (Process p in System.Diagnostics.Process.GetProcessesByName("Name of application"))
{
try
{
p.Kill();
// p.WaitForExit(); // possibly with a timeout
Application.Run(new Form1());
}
catch (Win32Exception winException)
{
// process was terminating or can't be terminated - deal with it
}
catch (InvalidOperationException invalidException)
{
// process has already exited - might be able to let this one go
}
}
}
//if (result == DialogResult.Cancel)
//{
//}
}
try
{
con123.Open();
con123.Close();
}
catch
{
MessageBox.Show("Cant connect to server!!!", "Error!");
Application.Exit();
}