Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Download Visual Studio Add-In

CreateMutex (kernel32)
 
.
Summary

C# Signature:

[DllImport("kernel32.dll")]
static extern IntPtr CreateMutex(IntPtr lpMutexAttributes, bool bInitialOwner,
   string lpName);

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.

//// Win32Calls.cs ////////////////////////////
namespace nsWin32Calls
{
    /// <summary>
    /// Win32 calls encapsulation object.
    /// </summary>
    public class Win32Calls
    {
        ...
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern IntPtr CreateMutex( IntPtr lpMutexAttributes,
            bool bInitialOwner, string lpName );

        [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.

                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.
                    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();
                }
            }
        }
        ...
    }
}

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

Alternative Managed API:

See
System.Threading.Mutex in .NET Framework 1.1
Documentation
CreateMutex on MSDN

Please edit this page!

Do you have...

  • 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).

 
Access PInvoke.net directly from VS:
Terms of Use
Find References
Show Printable Version
Revisions