UPDATED

After a lot of poking around on this subject I found a rather neat way of enforcing an application to behave in a single instance manner. I’ve only just started looking at this issue so I can’t vouch for its security at the moment but in light of a few examples I found this seems like a very simple solution.

A few of the examples included a fair amount of coding to achieve the Single Instance behaviour, including removing the App.xaml file altogether, I tried various things but some of the bindings I had setup really didn’t enjoy life after the App.xaml was taken from them.

[source:c-sharp] public partial class App : Application
{
public App() : base()
{
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName);
if (process.Length > 1)
{
MessageBox.Show(“MyApplication is already running …”, “MyApplication Launch”, MessageBoxButton.OK, MessageBoxImage.Information);
this.Shutdown();
}
}
}
[/source]

That is one way of achieving a single instance application.  However a far better solution is one that makes use of a Mutex.  This is far more robust and definitely the recommended approach for the majority of applications.  The code below is a static Main() method inside a WPF App class:

[source:c-sharp] private static bool isNew;

[System.STAThreadAttribute()] public static void Main()
{
using (Mutex m = new Mutex(true, “ThisIsTheStringMutexValueThatMustBeUnique”, out isNew))
{
if (isNew)
{
MyWPFApplication.App app = new MyWPFApplication.App();
app.InitializeComponent();
app.Run();
}
else
{
MessageBox.Show(“MyWPFApplication is already running!”, “MyWPFApplication”, MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
}
}
}
[/source]

Download FireFox 3 Today!!
Spore Creature Creator

Discussion

Leave a Comment

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.