Skip to content

Instantly share code, notes, and snippets.

@stuartd
Created March 7, 2012 15:28
Show Gist options
  • Save stuartd/1993803 to your computer and use it in GitHub Desktop.
Save stuartd/1993803 to your computer and use it in GitHub Desktop.
IntPtr hWnd = IntPtr.Zero;
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
foreach (Process process in processes)
{
// Get the first instance that is not this instance, has the
// same process name and was started from the same file name
// and location.
// Also check that the process has a valid
// window handle in this session to filter out other user's
// processes.
if (process.Id != currentProcess.Id
&& process.ProcessName == currentProcess.ProcessName
&& process.MainModule.FileName == currentProcess.MainModule.FileName
&& process.MainWindowHandle != IntPtr.Zero)
{
hWnd = process.MainWindowHandle;
break;
}
}
if (hWnd != IntPtr.Zero)
{
// Restore window if minimised. Do not restore if already in
// normal or maximised window state, since we don't want to
// change the current state of the window.
if (NativeMethods.IsIconic(hWnd) != 0)
{
NativeMethods.ShowWindow(hWnd, NativeMethods.SW_RESTORE);
}
// Set foreground window.
NativeMethods.SetForegroundWindow(hWnd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment