FREE hit counter and Internet traffic statistics from freestats.com

Tuesday, June 08, 2004

A Single Instance of a Windows Forms App

I noticed that on the Smart Client developer site on MSDN that Jonathan Wells answered the question regarding ensuring a single instance of a Windows Forms application. Awhile back I wrote a custom ApplicationContext class using ideas I read in an article I can't now locate. Anyway, here is the C# code for that class that allows you to pass a form and a flag to the Run method to disallow multiples. The default behavior is to disallow. This class uses the Mutex object as Jonathan mentions.



using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;

namespace AppContext
{

public class AppCtx : ApplicationContext
{
[DllImport("user32")]
private static extern bool SetForegroundWindow(IntPtr hwnd);

private AppCtx()
{}

private static Mutex s_Mutex;

public static void Run(Form mainForm)
{
run(mainForm,false);
}

public static void Run()
{
run(null,false);
}

public static void Run(Form mainForm, bool allowMultiples)
{
run(mainForm,allowMultiples);
}

private static void run(Form mainForm, bool allowMultiples)
{
if (!allowMultiples)
{
s_Mutex = new Mutex(true, Process.GetCurrentProcess().ProcessName);
if (s_Mutex.WaitOne(0,false))
{
if (mainForm == null)
Application.Run();
else
Application.Run(mainForm);
}
else
{
Process[] ps = Process.GetProcessesByName(
Process.GetCurrentProcess().ProcessName);
for (int i=0; i < ps.Length;i++)
{
if (ps[i].Id != Process.GetCurrentProcess().Id)
{
SetForegroundWindow(ps[i].MainWindowHandle);
}
}
}
}
else
Application.Run(mainForm);
}


public static void Exit()
{
Application.Exit();
}

}
}


The Main method would then look like so to disallow multiple instances of the app. Another great use of a custom app context would be to populate a custom IPrincipal object.


using System;

namespace AppContext
{
public class app
{
[STAThread]
static void Main()
{
Form1 f = new Form1();
AppCtx.Run(f,false);
}
}
}

1 comment:

Anonymous said...

What do you know Pirates of the Burning Sea Gold. And do you want to know? You can get potbs gold here. And welcome to our website, here you can play games, and you will get potbs Doubloon to play game. I know potbs money, and it is very interesting.Do you want a try, come and view our website, and you will learn how to buy potbs Doubloon. Come and join with us. We are waiting for your coming.