Could someone show how it is possible to check whether another instance of the program (e.g. test.exe) is running and if so stop the application from loading if there is an existing instance of it.
Want some serious code? Here it is.
var exists = System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1;
This works for any application (any name) and will become true
if there is another instance running of the same application.
Edit: To fix your needs you can use either of these:
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) return;
from your Main method to quit the method... OR
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) System.Diagnostics.Process.GetCurrentProcess().Kill();
which will kill the currently loading process instantly.
You need to add a reference to System.Core.dll for the .Count()
extension method. Alternatively, you can use the .Length
property.
It's not sure what you mean with 'the program', but if you want to limit your application to one instance then you can use a Mutex to make sure that your application isn't already running.
[STAThread] static void Main() { Mutex mutex = new System.Threading.Mutex(false, "MyUniqueMutexName"); try { if (mutex.WaitOne(0, false)) { // Run the application Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } else { MessageBox.Show("An instance of the application is already running."); } } finally { if (mutex != null) { mutex.Close(); mutex = null; } } }
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