c# - 如何确保单实例应用程序(在多个虚拟桌面上)?
问题描述
我正在编写一个 C# WinForms 应用程序,我需要确保在任何给定时间都有一个实例在运行。我以为我可以使用互斥锁。
这是我找到的链接: 如何将应用程序限制为仅一个实例。
当我使用单个桌面时,这很好用。但是,当 Windows 10 中打开了多个虚拟桌面时,这些桌面中的每一个都可以托管该应用程序的另一个实例。
有没有办法限制所有桌面上的单个实例?
解决方案
如果您查看文档的备注部分(请参阅Note
块) - 您会看到,您所要做的就是在互斥体前面加上"Global\"
. 这是 WinForms 的示例:
// file: Program.cs
[STAThread]
private static void Main()
{
using (var applicationMutex = new Mutex(initiallyOwned: false, name: @"Global\MyGlobalMutex"))
{
try
{
// check for existing mutex
if (!applicationMutex.WaitOne(0, exitContext: false))
{
MessageBox.Show("This application is already running!", "Already running",
MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
// catch abandoned mutex (previos process exit unexpectedly / crashed)
catch (AbandonedMutexException exception) { /* TODO: Handle it! There was a disaster */ }
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
推荐阅读
- highcharts - 更新图表的整个数据系列
- c - 为什么我的调试器在 switch 语句中的 case 之间错误地转换?
- reactjs - redux reducer 未收到操作
- c# - 通过代码创建 Azure ServiceBus 队列
- angular - 无法读取 collection.set() 上未定义的属性 afs (Angularfirestore)
- android - 将 DiffResult 分派到 RecyclerView 适配器后到底发生了什么
- html - 淡出所有内容,但悬停的链接在 Chrome 中不起作用
- java - 如何编写返回类型为 void 的测试用例 readFile 方法
- c# - View 显示 HTML 代码而不是呈现 HTML 代码
- excel - 当我循环通过列表时,VBA 打印输出代码会跳过打印纸