【发布时间】:2010-12-26 15:30:55
【问题描述】:
我已经成功地创建了一个这样的 .net 互斥锁: SingleIns = new Mutex(true, AppName); 一阵子。它适用于 XP、Vista,但显然不适用于 Windows7。所以我需要对 Win32 库进行互操作调用,以便其他 Com 组件可以识别互斥锁。我找到了以下代码,但是 Win32Calls。未找到...是否有我需要的程序集或参考? 提前致谢,
从以下位置找到代码: http://www.pinvoke.net/default.aspx/kernel32/CreateMutex.html
使用 System.Runtime.InteropServices;
[DllImport("kernel32.dll")]
public static extern IntPtr CreateMutex(IntPtr lpMutexAttributes, bool bInitialOwner, string lpName);
// create IntPtrs for use with CreateMutex()
IntPtr ipMutexAttr = new IntPtr( 0 );
IntPtr ipHMutex = new IntPtr( 0 );
try
{
// Create the mutex and verify its status BEFORE construction
// of the main form.
ipHMutex = Win32Calls.CreateMutex( ipMutexAttr,
true, "CompanyName_AppName_MUTEX" );
if (ipHMutex != (IntPtr)0)
{
// check GetLastError value (MUST use this call. See MSDN)
int iGLE = Marshal.GetLastWin32Error();
// if we get the ERROR_ALREADY_EXISTS value, there is
// already another instance of this application running.
if (iGLE == Win32Calls.ERROR_ALREADY_EXISTS)
// So, don't allow this instance to run.
return;
}
else
{ // CreateMutex() failed.
// once the app is up and running, I log the failure from
// within the frmMain constructor.
bool m_bMutexFailed = true;
}
// construct the main form object and
//form = new frmMain();
// run the app.
//Application.Run( form );
}
catch( Exception oEx )
{
//...handle it...
}
finally
{
// release the mutex
if (ipHMutex != (IntPtr)0)
Win32Calls.ReleaseMutex( ipHMutex );
// cleanup the main form object instance.
if (form != null) {
form.Dispose();
}
}
}
【问题讨论】:
-
嗯。我刚刚删除了 Win32Calls.CreateMutex 的 Win32Calls 部分并直接调用了 CreateMutex ......似乎它可能工作
-
您使用的是 64 位版本的 Windows 7 吗? .NET
Mutex在 Windows 7 中的工作原理与以前版本基本相同。 -
这是一个更好的参考...msdn.microsoft.com/en-us/library/…
-
是的,它是 64 位 Win7 机器...
-
如果您将平台目标设置为“x86”,.NET 互斥体是否按预期工作?您所看到的也可能是 32/64 位互操作问题(因为您提到了 COM,这只是一个想法)。
标签: .net com winapi interop mutex