I want to check when the user double click on applictaion icon that no another instance of this application is already running.
I read about My.Application but i still don't know what to do.
This is something I've used... (C# on .NET 2.0)
[STAThread]
private static void Main(string[] args)
{
//this follows best practices on
//ensuring that this is a single instance app.
string mutexName = "e50cf829-f6b9-471e-8d9f-67eac3699f09";
bool grantedOwnership;
//we prefix the mutexName with "Local\\" to allow this to run under terminal services.
//The "Local\\" prefix forces this into local user space.
//If we want to forbid this in TS, use the "Global\\" prefix.
Mutex singleInstanceMutex = new Mutex(true, "Global\\" + mutexName, out grantedOwnership);
try
{
if (!grantedOwnership)
{
MessageBox.Show("Error: X is already running.\n\nYou can only run one copy of X at a time.", "X", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
Application.Exit();
}
else
{
Application.Run(new X(args));
}
}
finally
{
singleInstanceMutex.Close();
}
}
In VB .NET there's a IsSingleInstance boolean property that does the job for you.
In VB (taken from here):
Public Class Program
Inherits Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
Public Sub New()
Me.IsSingleInstance = True
End Sub
End Class
Here's how you use it in C# (taken from here):
// SingleInstanceApplication.cs
class SingleInstanceApplication : WindowsFormsApplicationBase {
// Must call base constructor to ensure correct initial
// WindowsFormsApplicationBase configuration
public SingleInstanceApplication() {
// This ensures the underlying single-SDI framework is employed,
// and OnStartupNextInstance is fired
this.IsSingleInstance = true;
}
}
// Program.cs
static class Program {
[STAThread]
static void Main(string[] args) {
Application.EnableVisualStyles();
SingleInstanceApplication application =
new SingleInstanceApplication();
application.Run(args);
}
}
Make sure to reference the Microsoft.VisualBasic.dll in your project.
Open your Project Properties (Application Tab) and check the Make single instance application option.
From the Application tab, you can also click the View Application Events button, to create an ApplicationEvents.vb class where you can handle the second instance event:
Partial Friend Class MyApplication
Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
' Bring First Instance to Foreground
e.BringToForeground = True
' Pass Second Instance Command Line to First Instance
AppShared.DoSomethingWithCommandLine(e.CommandLine)
End Sub
End Class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With