Skip to content

Instantly share code, notes, and snippets.

@GenesisFR
Last active June 26, 2023 21:50
Show Gist options
  • Save GenesisFR/de0ad5710fb5eb221b5a239e819728bf to your computer and use it in GitHub Desktop.
Save GenesisFR/de0ad5710fb5eb221b5a239e819728bf to your computer and use it in GitHub Desktop.
C# method returning handles matching a given process name and class name
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace FindWindow
{
class FindWindow
{
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
public static List<IntPtr> GetWindowHandles(string processName, string className)
{
List<IntPtr> handleList = new List<IntPtr>();
Process[] processes = Process.GetProcessesByName(processName);
Process proc = null;
// Cycle through all top-level windows
EnumWindows(delegate (IntPtr hWnd, IntPtr lParam)
{
// Get PID of current window
GetWindowThreadProcessId(hWnd, out int processId);
// Get process matching PID
proc = processes.FirstOrDefault(p => p.Id == processId);
if (proc != null)
{
// Get class name of current window
StringBuilder classNameBuilder = new StringBuilder(256);
GetClassName(hWnd, classNameBuilder, 256);
// Check if class name matches what we're looking for
if (classNameBuilder.ToString() == className)
{
//Console.WriteLine($"{proc.ProcessName} process found with ID {proc.Id}, handle {hWnd.ToString("X")}");
handleList.Add(hWnd);
}
}
// return true so that we iterate through all windows
return true;
}, IntPtr.Zero);
return handleList;
}
}
class Program
{
static void Main(string[] args)
{
List<IntPtr> handles = FindWindow.GetWindowHandles("Spotify", "Chrome_WidgetWin_0");
}
}
}
@simsod
Copy link

simsod commented Jun 26, 2023

Thanks for this, needed it for moving a window where it was not the Process.MainWindowHandle, worked like a charm!

@GenesisFR
Copy link
Author

Thanks for this, needed it for moving a window where it was not the Process.MainWindowHandle, worked like a charm!

No problem, glad it helped someone else!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment