Sometimes we just want our program to open only one instance, that our software is opened only once. Then we can pass a way of knowing, before the software is not opened a open, not closed. That is, if there is another program is running.
The following is a simple method
// 确保不存在程序的其他实例
singleInstanceWatcher = new Semaphore(
0, // Initial count.
1, // Maximum count.
Assembly.GetExecutingAssembly().GetName().Name, out createdNew);
if (createdNew)
{
//之前没有运行过
}
else
{
//重复运行
MessageBox.Show("请不要重复运行(ノ`Д)ノ");
Environment.Exit(-2);
}
Another method
string mutexName = Properties.Resources.ProgramTitle + "Mutex";
singleInstanceWatcher = new Mutex(false, mutexName, out createdNew);
if (!createdNew)
{
MessageBox.Show("程序已经运行!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
Environment.Exit(-1);
}
bool createdNew;
System.Threading.Mutex instance = new System.Threading.Mutex(true, "MutexName", out createdNew);
if (createdNew)
{
Application.Run(new LoginForm());
instance.ReleaseMutex();
}
else
{
Application.Exit();
}
This article will be updated frequently, please read the original text: https://blog.lindexi.com/post/WPF-%E5%8F%AA%E5%85%81%E8%AE%B8%E6%89%93%E5% % 80% E4% BC B8% 80% E4% B8% E5% AE% AA% 9E% E4% BE% 8B.html , in order to avoid misleading the old error of knowledge, and a better reading experience.
If you want to continue to read my latest blog, please click on the RSS feed , it is recommended to use RSS Stalker subscribe to blog, or visit my homepage CSDN concern
This work is Creative Commons Attribution - NonCommercial - ShareAlike 4.0 International License Agreement for licensing. Welcome to reprint, use, repost, but be sure to keep the article signed by Linde Xi (containing links: https://blog.lindexi.com ), shall not be used for commercial purposes, be sure to publish the same work based on the paper license modification. If you have any questions, please contact me .
The following are advertising time
Recommended public concern Edi.Wang No.