Created
March 24, 2018 11:05
-
-
Save andylshort/ad073cb514054b21cfdb03971ba30efa to your computer and use it in GitHub Desktop.
Extension methods and useful features to add to WinForms projects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
namespace System.Windows.Forms.Helpers | |
{ | |
public class ApplicationHelper | |
{ | |
/// <summary> | |
/// Check if current process already running. If running, set focus to existing process and | |
/// returns <see langword="true"/> otherwise returns <see langword="false"/>. | |
/// </summary> | |
/// <returns><see langword="true"/> if it succeeds, <see langword="false"/> if it fails.</returns> | |
public static bool IsAlreadyRunning() | |
{ | |
/* | |
const int SW_HIDE = 0; | |
const int SW_SHOWNORMAL = 1; | |
const int SW_SHOWMINIMIZED = 2; | |
const int SW_SHOWMAXIMIZED = 3; | |
const int SW_SHOWNOACTIVATE = 4; | |
const int SW_RESTORE = 9; | |
const int SW_SHOWDEFAULT = 10; | |
*/ | |
const int swRestore = 9; | |
Process thisProcess = Process.GetCurrentProcess(); | |
Process[] processes = Process.GetProcessesByName(thisProcess.ProcessName); | |
if (processes.Length > 1) | |
{ | |
for (int i = 0; i < processes.Length; i++) | |
{ | |
if (processes[i].Id != thisProcess.Id) | |
{ | |
// Get the window handle | |
IntPtr hWnd = processes[i].MainWindowHandle; | |
// If iconic, restore the window | |
if (NativeMethods.IsIconic(hWnd)) | |
{ | |
NativeMethods.ShowWindowAsync(hWnd, swRestore); | |
} | |
// Bring it to the foreground | |
NativeMethods.SetForegroundWindow(hWnd); | |
break; | |
} | |
} | |
return true; | |
} | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment