Hi Alex,
Yes, a WinForms application written in VB.NEThave a specific application
framework, with which we could config a VB.NET application a single
instance application. Unfortunately, a WinForms application written in C#
doesn't have such a application framework.
A common way to make a application written in C# single instance is to make
use of Mutex, as Jon has suggested. You may add the following code to the
static Main method of the application.
using System.Threading;
[STAThread]
static void Main()
{
bool firstInstance;
Mutex mutex = new Mutex(false, "Local\\" +someUniqueName, out
firstInstance);
if (firstInstance)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
else
{
MessageBox.Show("An instance has already been run!");
}
}
If you're using VS05, you have another option, that is to use
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
class. We could derive a class from WindowsFormsApplicationBase class and
set the IsSingleInstance property to true.
The following is a sample. It requires that you add a reference to
'Microsoft.VisualBasic' to your C# project.
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;
class Program:WindowsFormsApplicationBase
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Program prog = new Program();
prog.EnableVisualStyles = true;
prog.MainForm = new Form1();
prog.Run(new string[] { ""});
}
public Program()
{
this.IsSingleInstance = true;
}
protected override void
OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
MessageBox.Show("another instance has been run!");
base.OnStartupNextInstance(eventArgs);
}
}
Hope this helps.
If you have anything unclear, please feel free to let me know.
Sincerely,
Linda Liu
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications.
Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.