I was wondering if someone can tell me what would be the best way to bring my application to the foreground if a mutex was not able to be created for a new instance.
E.g.: Application X is running but is in the background. I can't see it so I try to run another instance; because the mutex returns false, the best thing to do is to bring the existing instance to the foreground.
Anyone know the best way to interact with your own application but from a separate process?
You will need to get a hWnd to the other application's main window. The only way I remember how to do that is to loop over all windows until you find yours. There might be a more direct way
[DllImport("user32.dll")] private static extern
int EnumWindows(EnumWindowsProc ewp, int lParam);
public delegate bool EnumWindowsProc(int hWnd, int lParam);
public void EnumerateAllWindows()
{
EnumWindowsProc ewp = new EnumWindowsProc(EvalWindow);
EnumWindows(ewp, 0);
}
private bool EvalWindow(int hWnd, int lParam)
{
//this will be called for each window..
// use GetWindowThreadProcessId to get the PID for each window
// and use Process.GetProcessById to get the PID you are looking for
// then bring it to foregroun using of these calls below:
}
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
public static extern bool BringWindowToTop(IntPtr hWnd);
DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd