Last active
July 24, 2020 16:51
-
-
Save MoaidHathot/34d4e4a4f10ce2bc7232e3b679265f58 to your computer and use it in GitHub Desktop.
Script for bringing windows to the front
This file contains 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
void Main(string[] args) | |
{ | |
var mainTitle = args?.FirstOrDefault(); | |
var secondaryTitle = args?.Skip(1).FirstOrDefault(); | |
var processName = args?.Skip(2).FirstOrDefault(); | |
//Example | |
//(mainTitle, secondaryTitle, processName) = ("TechCrunch", "Startup", "chrome"); | |
BringToFront(mainTitle, secondaryTitle, processName); | |
} | |
[DllImport("user32.dll")] | |
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); | |
static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); | |
static readonly IntPtr HWND_TOP = new IntPtr(0); | |
static readonly IntPtr HWND_NOTOPMOST = new IntPtr(0); | |
const UInt32 SWP_NOSIZE = 0x0001; | |
const UInt32 SWP_NOMOVE = 0x0002; | |
const UInt32 SWP_SHOWWINDOW = 0x0040; | |
[DllImport("User32.dll", SetLastError = true)] | |
static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab); | |
[DllImport("user32.dll")] | |
public static extern bool SetForegroundWindow(IntPtr hWnd); | |
[DllImport("user32.dll")] | |
public static extern bool ShowWindow(IntPtr hWnd, uint flag); | |
const UInt32 SW_SHOW = 5; | |
const UInt32 SW_SHOWDEFAULT = 10; | |
const UInt32 SW_RESTORE = 9; | |
[DllImport("user32.dll", SetLastError = true)] | |
public static extern IntPtr SetActiveWindow(IntPtr hWnd); | |
[DllImport("user32.dll", SetLastError = true)] | |
internal static extern bool ShowWindowAsync(IntPtr windowHandle, uint nCmdShow); | |
public static void BringToFront(string mainTitle, string secondaryTitle, string processName) | |
{ | |
var process = Process | |
.GetProcesses() | |
.Where(x => x.MainWindowTitle.Contains(mainTitle, StringComparison.InvariantCultureIgnoreCase)) | |
.Where(x => string.IsNullOrWhiteSpace(processName) || (x.ProcessName?.Contains(processName, StringComparison.InvariantCultureIgnoreCase) ?? true)) | |
.FirstOrDefault(); | |
if(process is null) | |
{ | |
process = Process | |
.GetProcesses() | |
.Where(x => x.MainWindowTitle.Contains(secondaryTitle, StringComparison.InvariantCultureIgnoreCase)) | |
.Where(x => string.IsNullOrWhiteSpace(processName) || (x.ProcessName?.Contains(processName, StringComparison.InvariantCultureIgnoreCase) ?? true)) | |
.FirstOrDefault(); | |
if(process is null) | |
{ | |
return; | |
} | |
} | |
var handle = process.MainWindowHandle; | |
ShowWindowAsync(handle, SW_SHOW); | |
SetForegroundWindow(handle); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment