Code Snippet: Restrict to your application to one instance.
简单来说,这段代码调用 Win32API CreateEvent Function 创建一个全局的Event 对象。
如果这个对象已经存在,GetLastError 会返回 183 ERROR_ALREADY_EXISTS。个人意见以为这个方法比满世界地找Handle 用起来舒服。SECURITY_ATTRIBUTES attributes = new SECURITY_ATTRIBUTES();
SECURITY_DESCRIPTOR descriptor = new SECURITY_DESCRIPTOR();
![]()
IntPtr sharedFile = IntPtr.Zero;
IntPtr pDescriptor = IntPtr.Zero;
IntPtr pAttributes = IntPtr.Zero;
try
...{
pDescriptor = Marshal.AllocHGlobal(Marshal.SizeOf(descriptor));
pAttributes = Marshal.AllocHGlobal(Marshal.SizeOf(attributes));
![]()
attributes.nLength = Marshal.SizeOf(attributes);
attributes.bInheritHandle = true;
attributes.lpSecurityDescriptor = pDescriptor;
![]()
if (!InterOp.InitializeSecurityDescriptor(ref descriptor, 1 /**//*SECURITY_DESCRIPTOR_REVISION*/))
throw new ApplicationException("InitializeSecurityDescriptor failed: " + Marshal.GetLastWin32Error());
![]()
if (!InterOp.SetSecurityDescriptorDacl(ref descriptor, true, IntPtr.Zero, false))
throw new ApplicationException("SetSecurityDescriptorDacl failed: " + Marshal.GetLastWin32Error());
![]()
Marshal.StructureToPtr(descriptor, pDescriptor, false);
Marshal.StructureToPtr(attributes, pAttributes, false);
![]()
bufferEvent = InterOp.CreateEvent(pAttributes, false, false, "Your Name Here");
![]()
if (bufferEvent == IntPtr.Zero)
throw new ApplicationException("CreateEvent (bufferEvent) failed: " + Marshal.GetLastWin32Error());
![]()
if (Marshal.GetLastWin32Error() == 183 /**//*ERROR_ALREADY_EXISTS*/)
// Another instance is running, add your code here.
}
finally
...{
Marshal.FreeHGlobal(pDescriptor);
Marshal.FreeHGlobal(pAttributes);
}
上面代码用到的几个Win32 Function/结构的定义:...{internal abstract class InterOp
![]()
[DllImport("advapi32.dll", SetLastError=true)]
internal static extern bool InitializeSecurityDescriptor([In] ref SECURITY_DESCRIPTOR pSecurityDescriptor, int dwRevision);
![]()
[DllImport("advapi32.dll", SetLastError=true)]
internal static extern bool SetSecurityDescriptorDacl
([In] ref SECURITY_DESCRIPTOR pSecurityDescriptor,
bool bDaclPresent,
IntPtr pDacl,
bool bDaclDefaulted);
![]()
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
internal static extern IntPtr CreateEvent(IntPtr lpEventAttributes, bool bManualReset, bool bInitialState, string lpName);
}
![]()
internal struct SECURITY_DESCRIPTOR
...{
internal byte Revision;
internal byte Sbz1;
internal short Control;
internal IntPtr Owner;
internal IntPtr Group;
internal IntPtr Sacl;
internal IntPtr Dacl;
}
![]()
internal struct SECURITY_ATTRIBUTES
...{
internal int nLength;
internal IntPtr lpSecurityDescriptor;
internal bool bInheritHandle;
}
代码来源自 ClrSpy 源代码。
posted on 2005-02-26 04:11:00 by zee 评论(4) 阅读(5542)


pDescriptor 
}