Created
January 20, 2018 00:04
-
-
Save avspeed/f87839064d0d8df222ab5ffe199259be to your computer and use it in GitHub Desktop.
Enumerate open windows
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
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