I\'ve been successfully creating a .net mutex like this: SingleIns = new Mutex(true, AppName); for a while. It works in XP, Vista, but apparently not in Windows7. So I nee
It doesn't compile because the CreateMutex declaration is not in the Win32Calls namespace. Next problem is that it still won't work as intended because the [DllImport] declaration is missing the SetLastError property assignment. 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.