blez's : blog

code / design / music and more

How to get all topmost windows and the current one

Leave a comment

The following code enumerates all topmost windows and marks the current one with “>”

using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections.Generic;

namespace EnumWnd {
    class Program {
        static void Main(string[] args) {
            var windows = GetAllWindows();
            foreach (var window in windows) {
                int size = GetWindowTextLength(window);
                if (size++ > 0 && IsWindowVisible(window)) {
                    var builder = new StringBuilder(size);
                    GetWindowText(window, builder, size);

                    // this marks the foreground window
                    if (window == GetForegroundWindow()) {
                        Console.WriteLine("> " + builder.ToString());
                    } else {
                        Console.WriteLine(builder.ToString());
                    }                    
                }
            }

            Console.ReadKey();
        }

        #region private definitions
        private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder strText, int maxCount);
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        private static extern int GetWindowTextLength(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
        [DllImport("user32.dll")]
        private static extern bool IsWindowVisible(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        private static List<IntPtr> hWnds = new List<IntPtr>();

        private static bool EnumTheWindows(IntPtr hWnd, IntPtr lParam) {
            hWnds.Add(hWnd);
            return true;
        }

        private static List<IntPtr> GetAllWindows() {
            EnumWindows(new EnumWindowsProc(EnumTheWindows), IntPtr.Zero);
            return hWnds;
        }
        #endregion
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s