App.xaml.cs
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
private const int WS_SHOWNORMAL = 1;
public App()
{
...
this.Startup += new StartupEventHandler(App_Startup);
//notify exception that throw in the code and not try catch
DispatcherunhandledException += Application_DispatcherUnhandledException; //UI Exception
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
...
}
void App_Startup(object sender, StartupEventArgs e)
{
Process instance = RunningInstance();
if(instance == null){}
else
{
ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
SetForegroundWindow(instance.MainWindowHandle);
Environment.Exit(0);
}
}
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
foreach (var p in processes)
{
if (p.Id != current.Id)
{
if( (Assembly.GetExecutingAssembly().Location.Replace("/","\\") == current.MainModule.FileName)
{
return p;
}
}
}
}