我一直在成功地創建一個.net互斥體,如下所示: SingleIns = new Mutex(true,AppName); 一段時間。它適用於XP,Vista,但顯然不適用於Windows7。所以我需要對Win32庫進行互操作,以便其他Com組件可以識別互斥鎖。我發現了下面的代碼,但是Win32Calls。沒有找到...有我需要的裝配或參考嗎? 由於提前,如何從.Net打電話給win32 CreateMutex
實測值代碼:使用System.Runtime.InteropServices http://www.pinvoke.net/default.aspx/kernel32/CreateMutex.html
;
[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 direct ...似乎可能會起作用 – mytwocents 2009-12-15 00:36:45
您是否使用64位版本的Windows 7? .NET'Mutex'應該在Windows 7中基本上與以前的版本一樣。 – 2009-12-15 00:49:59
這是一個更好的參考... http://msdn.microsoft.com/en-us/library/microsoft.win32.safehandles.safewaithandle.aspx – mytwocents 2009-12-15 01:06:45