问题描述
我一定要限制我的.NET 4的WPF应用程序,以便它可以在每台机器只运行一次。请注意,我说的每台机器,而不是每个会话。
我实现了使用简单的互斥直到现在单实例应用程序,但不幸的是这样一个互斥体是每个会话。
I have to restrict my .net 4 WPF application so that it can be run only once per machine. Note that I said per machine, not per session.
I implemented single instance applications using a simple mutex until now, but unfortunately such a mutex is per session.
有没有一种方法来创建一个计算机范围互斥或者是有来实现每台机器的应用程序的单一实例的任何其他解决办法?
Is there a way to create a machine wide mutex or is there any other solution to implement a single instance per machine application?
推荐答案
我会做到这一点与必须保持你的应用程序的生命一个全局互斥对象。
I would do this with a global Mutex object that must be kept for the life of your application.
MutexSecurity oMutexSecurity;
//Set the security object
oMutexSecurity = new MutexSecurity();
oMutexSecurity.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), MutexRights.FullControl, AccessControlType.Allow));
//Create the global mutex and set its security
moGlobalMutex = new Mutex(True, "Global\\{5076d41c-a40a-4f4d-9eed-bf274a5bedcb}", bFirstInstance);
moGlobalMutex.SetAccessControl(oMutexSecurity);
其中, bFirstInstance
返回,如果这是你的应用程序在全球运行的第一个实例。如果你省略了互斥的全球部分或局部替换它,然后互斥量将只有每节(这是proberbly如何你目前的code的工作)。
Where bFirstInstance
returns if this is the first instance of your application running globally. If you omited the Global part of the mutex or replaced it with Local then the mutex would only be per session (this is proberbly how your current code is working).
我相信,我第一次来到这个技术从乔恩斯基特。
I believe that I got this technique first from Jon Skeet.
在互斥对象上的MSDN主题介绍有关这两个作用域一个互斥对象和亮点为什么使用终端服务时,这是很重要的(见第二到最后一个音符)。
The MSDN topic on the Mutex object explains about the two scopes for a Mutex object and highlights why this is important when using terminal services (see second to last note).
这篇关于如何实现每台机器的应用程序单个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!