Skip to content

Instantly share code, notes, and snippets.

@avspeed
Created January 20, 2018 00:04
Show Gist options
  • Save avspeed/f87839064d0d8df222ab5ffe199259be to your computer and use it in GitHub Desktop.
Save avspeed/f87839064d0d8df222ab5ffe199259be to your computer and use it in GitHub Desktop.
Enumerate open windows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AVSPEED.Helper
{
using System.Runtime.InteropServices;
using HWND = IntPtr;
/// <summary>Contains a method to get all the open windows.</summary>
public static class OpenWindowGetter
{
/// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary> /// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
public static IDictionary<HWND, string> GetOpenWindows()
{
HWND lShellWindow = GetShellWindow();
Dictionary<HWND, string> lWindows = new Dictionary<HWND, string>();
EnumWindows(delegate (HWND hWnd, int lParam)
{
if (hWnd == lShellWindow) return true;
if (!IsWindowVisible(hWnd)) return true;
int lLength = GetWindowTextLength(hWnd);
if (lLength == 0) return true;
StringBuilder lBuilder = new StringBuilder(lLength);
GetWindowText(hWnd, lBuilder, lLength + 1);
lWindows[hWnd] = lBuilder.ToString();
return true;
}, 0);
return lWindows;
}
delegate bool EnumWindowsProc(HWND hWnd, int lParam);
[DllImport("USER32.DLL")]
static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);
[DllImport("USER32.DLL")]
static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("USER32.DLL")]
static extern int GetWindowTextLength(HWND hWnd);
[DllImport("USER32.DLL")]
static extern bool IsWindowVisible(HWND hWnd);
[DllImport("USER32.DLL")]
static extern IntPtr GetShellWindow();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment