Wednesday, 30 November 2011

Code for Opening Single instance in windows application using C# and VB.NET

VB.Net::
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
If Not InstanceRunning() Then

Else
'MessageBox.Show("Process is already running ")
Me.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
Private ReadOnly Property InstanceRunning() As Boolean
Get
Dim strProcessName As String = System.Diagnostics.Process.GetCurrentProcess().ProcessName
Dim processes As System.Diagnostics.Process() = System.Diagnostics.Process.GetProcessesByName(strProcessName)
Return (processes.Length > 1)
End Get
End Property


C#.NET:   

 # region Single Instance
            // allowing only single instance of the application to run.
            string processName = Process.GetCurrentProcess().ProcessName;
            Process[] instances = Process.GetProcessesByName(processName);

            if (instances.Length > 1)
            {
                MessageBox.Show("This application is already running !!!", "TippingPointes MMS", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Process.GetCurrentProcess().Close();
                return;
            }
            # endregion


No comments:

Post a Comment