Help w/ Single Instance

W

wg

I am attempting to prevent a second instance of my application from
starting. I have the following code at the beginning of Form_Load
If Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length
Me.Close()
Application.Exit()
Logger.LogMessage("FormLoad", "Second instance of application attempted")
End If
I know that it is going into the If-Then condition because it writes to my
logger. But the 2nd application still starts up. Should I set the startup to
Sub Main? Or can anyone offer suggestions?

Thanks

wg
 
H

Herfried K. Wagner [MVP]

wg said:
I am attempting to prevent a second instance of my application from
starting. I have the following code at the beginning of Form_Load
If
Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length
Me.Close()
Application.Exit()
Logger.LogMessage("FormLoad", "Second instance of application attempted")
End If
I know that it is going into the If-Then condition because it writes to my
logger. But the 2nd application still starts up. Should I set the startup
to Sub Main? Or can anyone offer suggestions?

I suggest to put the code in the 'Sub Main' instead of the form, because it
doesn't make much sense to load the form if it should not be shown.
Additionally it's not guaranteed that the 'ProcessName' is unique for your
application, especially if you are using a simple name like "Calculator".
Using a mutex will help to avoid this problem:

<URL:http://www.yoda.arachsys.com/csharp/faq/#one.application.instance>
 
W

wg

Thanks for the help, this worked great.


wg


wg said:
I am attempting to prevent a second instance of my application from
starting. I have the following code at the beginning of Form_Load
If
Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length
Me.Close()
Application.Exit()
Logger.LogMessage("FormLoad", "Second instance of application attempted")
End If
I know that it is going into the If-Then condition because it writes to my
logger. But the 2nd application still starts up. Should I set the startup
to Sub Main? Or can anyone offer suggestions?

Thanks

wg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top