I have a wpf app and I have to make the app to be run only once. There shouldnt be more than one instance on one machine.
Here's my code in App.xaml.cs, in the OnStartup() method:
var runningProcess = GetAnotherAppInstanceIfExists();
if (runningProcess != null)
{
HandleMultipleInstances(runningProcess);
Environment.Exit(0);
}
public Process GetAnotherAppInstanceIfExists()
{
var currentProcess = Process.GetCurrentProcess();
var appProcesses = new List<string> { "myApp", "myApp.vshost" };
var allProcesses = Process.GetProcesses();
var myAppProcess = (from process in allProcesses
where process.Id != currentProcess.Id && appProcesses.Contains(process.ProcessName)
select process).FirstOrDefault();
if (myAppProcess != null)
{
return currentProcess;
}
return myAppProcess;
}
public void HandleMultipleInstances(Process runningProcess)
{
SetForegroundWindow(runningProcess.MainWindowHandle);
ShowWindow(runningProcess.MainWindowHandle, SW_RESTORE);
}
So the app, when run for the second time, doesnt open a new instance, which is great. However, I need to find the first instance and show the window again, if it is minimized. This line is for that:
ShowWindow(runningProcess.MainWindowHandle, SW_RESTORE);
and it doesn't work. What am I doing wrong? I looked at a lot of examples online and my code is the same as them.