如何获得所有打开窗口的List <string>?</string>

时间:2014-08-19 11:33:22

标签: c# .net

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


/// <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>

    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);

    public static string GetWindowText(IntPtr hWnd)
    {
        int size = GetWindowTextLength(hWnd);
        if (size++ > 0)
        {
            var builder = new StringBuilder(size);
            GetWindowText(hWnd, builder, builder.Capacity);
            return builder.ToString();
        }

        return String.Empty;
    }

    public static IEnumerable<IntPtr> FindWindowsWithText()//string titleText)
    {
        IntPtr found = IntPtr.Zero;
        List<IntPtr> windows = new List<IntPtr>();

        EnumWindows(delegate(IntPtr wnd, IntPtr param)
        {
            //if (GetWindowText(wnd).Contains(titleText))
            //{
                windows.Add(wnd);
            //}
            return true;
        },
                    IntPtr.Zero);

        return windows;
    }
}

返回IntPtr列表,但我想知道窗口是浏览器还是程序,窗口名称/文本是什么。

我在form1中使用它,如下所示:

var windows = OpenWindowGetter.FindWindowsWithText();

为什么它会返回339项(窗口)?我没有打开339个窗户。

0 个答案:

没有答案