Is my app already running? Well, it shouldn't be. [blameMike]
Is my app already running? Well, it shouldn't be.
"if (Diagnostics.Process.GetProcessByName(Application.ProductName).Length > 1)
{
MessageBox.Show(Application.ProductName + " is already running.",Application.ProductName,MessageBoxButtons.OK, MessageBoxIcon.Warning);
Application.Exit();
}"
Looks like an easier way to implement a singleton application model than a mutex...?
(Via blameMike)
2 comments:
I believe it should be GetProcessesByName rather than GetProcessByName, at least it is in VB.Net.
Here is some VB.Net code. However this doesn't necessarily work unless the assembly name is equal to the rootspace name. Under the solution(project) properties there is an "Assembly name" and currentProcess.ProcessName takes on the "Assembly Name" while Application.ProductName takes on the "Root Namespace" so unless these two are the same, the code won't work. Correct VB code with comments/explanations is below:
Mark Hayworth
P.S. Thanks for the code though. I learned something new and will put it to use.
' Exit if program is already running.
' Get the current process.
Dim currentProcess As System.Diagnostics.Process = Process.GetCurrentProcess()
Dim AllProcessesOfThisApp() As System.Diagnostics.Process
Dim intNumberOfProcessesOfThisApp As Integer
' Check for a process named the same as the Application.ProductName.
' This will be the "Root namespace" in the Solution Properties dialog box.
' This will not equal the process name unless the Root namespace is the same
' as the "Assembly name" in the dialog box.
' Commented out because it doesn't work.
'AllProcessesOfThisApp = System.Diagnostics.Process.GetProcessesByName(Application.ProductName)
' Check for a process named the same as this process's name, which is the
' same as the "Assembly name" in the Solution Project Properties dialog box.
AllProcessesOfThisApp = System.Diagnostics.Process.GetProcessesByName(currentProcess.ProcessName)
intNumberOfProcessesOfThisApp = AllProcessesOfThisApp.Length() ' Find out how many there are.
If intNumberOfProcessesOfThisApp > 1 Then
MessageBox.Show(Application.ProductName + " is already running.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning)
Application.Exit()
End If
Great comment... Thank you.
That's what I get for cutting-n-pasting without trying it myself... :0
Post a Comment