Type a page name and press Enter. You'll jump to the page if it exists, or you can create it if it doesn't.
To create a page in a module other than kernel32, prefix the name with the module name and a period.
<DllImport("Kernel32.dll", CharSet:=CharSet.Auto, setlasterror:=True)> _
Public Function CreateMutex(ByVal lpMutexAttributes As IntPtr, _
ByVal bInitialOwner As Boolean, _
ByVal lpName As String) As IntPtr
End Function
User-Defined Types:
None.
Notes:
None.
Tips & Tricks:
Please add some!!!
Sample Code:
Here's how I use CreateMutex() to prevent more than one instance of my application from running at any given time.
[DllImport("kernel32.dll")]
public static extern bool ReleaseMutex( IntPtr hMutex );
...
/// <summary>
/// This value can be returned by CreateMutex() and is found in
/// C++ in the error.h header file.
/// </summary>
public const int ERROR_ALREADY_EXISTS = 183;
...
}
}
//// frmMain.cs ///////////////////////////////
...
using nsWin32Calls; // encapsulates Win32 calls
...
namespace dsh
{
public class frmMain : System.Windows.Forms.Form
{
...
// helper objects
private static frmMain form = null;
...
/// <summary>
/// Main entry point for the application.
/// </summary>
[STAThread]
public static void Main()
{
// 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.
if (ipHMutex != IntPtr.Zero)
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.
m_bMutexFailed = true;
}
// construct the main form object and
form = new frmMain();
// cleanup the main form object instance.
if (form != null) {
form.Dispose();
}
}
}
...
}
}
I tried to format as well as possible, but this thing is a bit weird. If I leave one blank line, this darn thing leaves two. If I leave none, it leaves none. :s
Another Sample implementation
This implements a Mutex using a Null DACL (with all the security problems with that). This allows the Mutex to be sharable cross-process. In my implementation I access this Mutex from both ASP.Net and a Windows service running under different ids.
I put this together from links on this site as well as searching other sites. Credit to all those who posted to help me implement this.
/// <summary>
/// Summary description for Native.
/// </summary>
internal sealed class Native
{
/// <summary>
/// This value can be returned by CreateMutex() and is found in
/// C++ in the error.h header file.
/// </summary>
public const int ERROR_ALREADY_EXISTS = 183;
public const uint SYNCHRONIZE = 0x00100000;
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct SECURITY_DESCRIPTOR
{
public byte revision;
public byte size;
public short control;
public IntPtr owner;
public IntPtr group;
public IntPtr sacl;
public IntPtr dacl;
}
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
public class SecurityNeutralMutex
{
[ Serializable ]
public class MutexCreationException : ApplicationException
{
public MutexCreationException( string msg ) : base( msg )
{
}
public MutexCreationException( string msg, Exception ex ) : base( msg, ex )
{
}
if( hMutex == IntPtr.Zero )
{
// If we get here, some sort of unrecoverable error has presumably occurred.
// However, we will try one last time, in case it was merely some sort of race condition.
// Note that I do not believe that there is any opening for a race condition in the above code.
// Nevertheless, we have nothing to lose by giving it one last try.
hMutex = Native.OpenMutex( ( uint ) ( Native.SyncObjectAccess.MUTEX_MODIFY_STATE ), false, name );
createdNew = false;
if( hMutex == IntPtr.Zero )
{
lastError = Marshal.GetLastWin32Error();
throw new MutexCreationException( string.Format( "Unable to create or open mutex. Win32 error num: '{0}'", lastError ) );
}
}
}
helpful tips or sample code to share for using this API in managed code?
corrections to the existing content?
variations of the signature you want to share?
additional languages you want to include?
Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).