Tuesday, 4 October 2011

Get List of open windows in a machine including pop up windows

class Program
foreach (KeyValuePair<IntPtr, string>lWindow in OpenWindowGetter.GetOpenWindows())

IntPtr lHandle = lWindow.Key;
string lTitle = lWindow.Value;
Console.WriteLine("{0}: {1}", lHandle, lTitle);}}

using System;

using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace GetOpenWindows
using HWND = IntPtr;/// Contains a method to get all the open windows.
public static class OpenWindowGetter{/// Returns a dictionary that contains the handle and title of all the open windows./// A dictionary that contains the handle and title of all the open windows.
    EnumWindows(delegate(HWND hWnd, int lParam)
        if (hWnd == lShellWindow) return true;

        if (!IsWindowVisible(hWnd)) return true;
        int processId;
        processId= GetWindowThreadProcessId(hWnd,out processId);
        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);

static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);

static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount);

static extern int GetWindowTextLength(HWND hWnd);

static extern int GetWindowThreadProcessId(HWND hWnd, out int processId);

static extern bool IsWindowVisible(HWND hWnd);

static extern IntPtr GetShellWindow();


Md. Jawed