While enhancing the Weed Killer application, I ran into an interesting problem trying to make Weed Killer a single instance application.  There are several ways to do this: one is to use the semi-dreaded mutex. Surprisingly, the easiest way turned out to be implementing a class in the Microsoft.VisualBasic namespace from the .NET 2.0 framework: WindowsFormsApplicationBase.

But, at first, it may not seem like the easiest way.  I had to make several attempts to get my inheriting class right.  I ran into a lot of examples on the net which were not great fits for what I was trying to do.  And some of the examples were right in principal, but the code didn’t work.

The class shown here can be used for your own code, by just replacing the form you instantiate in the startup event.  ManagerMDI is the entry point for the application.  Its method OpenFile() takes a single parameter: the file to open.  It internally manages whether the file is already open in a child window, or if a new window needs to be open.

The value of inheriting from the WindowsFormsApplicationBase base class is obvious: all of the housekeeping for determining whether an instance is running or not is taken care of for the developer.  The two startup cases are handled easily using specific events: Startup if you’re the first, or StartupNextInstance if you’re not the first.

One little note:  The method SetForegroundWindow() from user32.dll is used to set focus on the application, at the end of the StartupNextInstance event.  I also use it in the Startup event, in case the application was launched from an outside source (e.g. Windows Explorer context) though it probably isn’t needed there.  The behavior of this method is dependent on a setting for limiting focus, which you can see in Powertoys for WinXP, etc (General / Focus).  If “prevent applications from stealing focus” is enabled, the method will cause the application’s taskbar entry to flash.  When disabled, the application will be restored and receive focus on the desktop.