How to call win32 CreateMutex from .Net

久未见 提交于 2019-11-29 12:57:36

It doesn't work is because you CreateMutex declaration is not in the Win32Calls namespace. Your next problem is that it still won't work because you forgot to set the SetLastError property in the [DllImport] attribute. Required to make Marshal.GetLastWin32Error() return the error.

Rewinding a bit, using the Mutex class in Win7 should work without a problem. The only failure mode I can think of is not prefixing the mutex name with "Global\" so the mutex is visible in all sessions. That's a bit remote.

More to the point, you are trying to do something that is already very well supported in the .NET framework. Project + Add Reference, select Microsoft.VisualBasic. Make your Program.cs code look like this:

using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;

namespace WindowsFormsApplication1 {
  class Program : WindowsFormsApplicationBase {
    [STAThread]
    static void Main(string[] args) {
      var prog = new Program();
      prog.EnableVisualStyles = true;
      prog.IsSingleInstance = true;
      prog.MainForm = new Form1();
      prog.Run(args);
    }
  }
}

Bonus goodies with this approach is that it automatically sets the focus to the running instance of your program when the user starts it again. And you can override the OnStartupNextInstance method to know what command line arguments were used and respond accordingly.

In case it might help you, the .NET Framework already provides a wrapper of the Win32 mutex object. See System.Threading.Mutex. All of the major functionality is there, including the ability to use prefixes like "Global\".

Should be as simple as:

private static System.Threading.Mutex _mutex = null;

const string guid = "{...GUID...}";
bool createdNew;

_mutex = new Mutex(true, guid, out createdNew);

if (!createdNew) {
    // it is in use already
}

system wide mutex creation - ownership: https://stackoverflow.com/a/3111740/1644202

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!