Single Instance Application
Sometime we come across a situation where we have to develop a single instance application. It can be achieved in many ways, one among them is using Mutex.
Microsoft has provided an easy solution via Microsoft.VisulaBasic.ApplicationService namesapce.
MySingleInstanceClass
This class takes care of the application instances. This class should be derived from Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.
using System;
using Microsoft.VisualBasic.ApplicationServices;
namespace Surya
{
public class MySingleInstanceClass: WindowsFormsApplicationBase
{
Form1 MainForm;
public MySingleInstanceClass()
{
// Set whether the application is single instance
this.IsSingleInstance = true;
//register for the Startup next instance event.
this.StartupNextInstance += new
StartupNextInstanceEventHandler(this_StartupNextInstance);
}
void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)
{
//When next instance is launched use the MainForm instance already created and call
//a public Load function with the command line arguments.
Form1 form = MainForm as Form1;
form.Load(e.CommandLine[1]);
}
protected override void OnCreateMainForm()
{
// Instantiate your main application form
this.MainForm = new Form1();
}
}
}
//Now change you main function. Instead of using Application.Run(..) use //following
[STAThread]
static void Main()
{
string[] args = Environment.GetCommand
MySingleInstanceClass instance = new MySingleInstanceClass();
instance.Run(args);
}
Now our Form1 is a simple form with one Load function to take care of subsequent application launch.
using System;
using System.Windows.Forms;
namespace Surya
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
string[] args = Environment.GetCommandLineArgs();
Load(args[1]);
}
public void Load(string args)
{
//when an instance is launched args are shown in a TextBox.
//Here you can implement the logic like if the application is open and if there is
//unsaved data before Loading the new file you can ask the user to Save and then
//Load or Discard and Load.
textBox1.Text = args;
}
}
}
This completes the Single Instance application implementation in C# using VB Application Services namesapce.