[Mono-list] howto don't allow to execute program two times?

Engler, Eric Eric.Engler at zcsterling.com
Wed Sep 19 17:16:05 EDT 2007

Hash: SHA256

I am not doing this in Mono yet, but here's the code I have for Windows.

This code came from here:

The first function detects if another instance is running. The caller of
this function can then take action: typically he'll just end his own
program. Or he may want to pop-up the other instance that's already
running before he exits (far less portable - see below).

This function uses a Mutex, which may be portable to Mono:

private static Mutex mutex = null;

// Determine if the current process is already running
public static bool ThisProcessIsAlreadyRunning()
  // Only want to call this method once, at startup.
  Debug.Assert(mutex == null);
  // createdNew needs to be false in .Net 2.0, otherwise, if another
instance of
  // this program is running, the Mutex constructor will block, and then
  // an exception if the other instance is shut down.
  bool createdNew = false;
  mutex = new Mutex(false, "PgmName Mutex", out createdNew);

  Debug.Assert(mutex != null);
  return !createdNew;

Here's the Windows code that can be used to pop-up the other instance.
This is full of non-portable API calls, so I hope someone can help to
make these work with Mono:

  [DllImport("user32.dll", SetLastError = true)]
  static extern int FindWindow(string lpClassName, string lpWindowName);

  [return: MarshalAs(UnmanagedType.Bool)]
   static extern bool SetForegroundWindow(int hWnd);

  static extern bool IsIconic(int hWnd);

  static extern bool ShowWindow(int hWnd, int nCmdShow);

  const int SW_RESTORE = 9;

  static extern int GetLastActivePopup(int hWnd);

  static extern bool IsWindowEnabled(int hWnd);

  // Set focus to the previous instance of the specified program.
  public static void SetFocusToPreviousInstance(string windowCaption)
     // Look for previous instance of this program. 
     int hWnd = FindWindow(null, windowCaption);
     // If a previous instance of this program was found...
     if (hWnd != 0)
         // Is it displaying a popup window?
         int hPopupWnd = GetLastActivePopup(hWnd);
         // If so, set focus to the popup window. Otherwise set focus
         // to the program's main window.
         if (hPopupWnd != 0 && IsWindowEnabled(hPopupWnd))
            hWnd = hPopupWnd;
         // If program is minimized, restore it.
         if (IsIconic(hWnd))
           ShowWindow(hWnd, SW_RESTORE);

Version: PGP Universal 2.6.2
Charset: us-ascii


More information about the Mono-list mailing list