How do I check if my C# Windows application is running ?
I know that I can check the process name but the name can be changed if the exe changes.
Is there any way to have a hash key or something to make my application unique?
You can start Task Manager by pressing the key combination Ctrl + Shift + Esc. You can also reach it by right-clicking on the task bar and choosing Task Manager. Under Processes>Apps you see the software that is currently open. This overview should be straight forward these are all the programs you are currently using.
Select Start , then select Settings > Privacy > Background apps. Under Background Apps, make sure Let apps run in the background is turned On. Under Choose which apps can run in the background, turn individual apps and services settings On or Off.
public partial class App : System.Windows.Application { public bool IsProcessOpen(string name) { foreach (Process clsProcess in Process.GetProcesses()) { if (clsProcess.ProcessName.Contains(name)) { return true; } } return false; } protected override void OnStartup(StartupEventArgs e) { // Get Reference to the current Process Process thisProc = Process.GetCurrentProcess(); if (IsProcessOpen("name of application.exe") == false) { //System.Windows.MessageBox.Show("Application not open!"); //System.Windows.Application.Current.Shutdown(); } else { // Check how many total processes have the same name as the current one if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1) { // If ther is more than one, than it is already running. System.Windows.MessageBox.Show("Application is already running."); System.Windows.Application.Current.Shutdown(); return; } base.OnStartup(e); } }
The recommended way is to use a Mutex. You can check out a sample here : http://www.codeproject.com/KB/cs/singleinstance.aspx
In specific the code:
/// /// check if given exe alread running or not /// /// returns true if already running private static bool IsAlreadyRunning() { string strLoc = Assembly.GetExecutingAssembly().Location; FileSystemInfo fileInfo = new FileInfo(strLoc); string sExeName = fileInfo.Name; bool bCreatedNew; Mutex mutex = new Mutex(true, "Global\\"+sExeName, out bCreatedNew); if (bCreatedNew) mutex.ReleaseMutex(); return !bCreatedNew; }
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