将所有文本写入 window

get all text written inside a window

我想获取 window 的所有文本。

我准备了下面code.But我只能得到windowcaptions/titles.

如何将所有文本写在 window 中?

    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern int GetWindowTextLength(IntPtr hWnd);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

       Process[] processlist = Process.GetProcesses();

        foreach (Process process in processlist)
        {
            if (!String.IsNullOrEmpty(process.MainWindowTitle))
            {
                IntPtr xero = new IntPtr(0);
                var x = FindWindowByCaption(xero, process.MainWindowTitle);
                int length = GetWindowTextLength(x);
                StringBuilder sb = new StringBuilder(length + 1);
                GetWindowText(x, sb, sb.Capacity);
            }
        }

您需要枚举顶级 windows 的所有子级 windows。您可以使用 EnumChildWindows API 来实现这一点。

这是我用 C# 为您编写的示例代码

internal class Program
{
    public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool EnumChildWindows(IntPtr hWndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);

    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, StringBuilder lParam);

    const uint WM_GETTEXT = 0x000D;

    static bool EnumAllChilds(IntPtr hWnd, IntPtr lParam)
    {
        StringBuilder sb = new StringBuilder(2048);

        SendMessage(hWnd, WM_GETTEXT, new IntPtr(sb.Capacity), sb);

        if (!string.IsNullOrEmpty($"{sb}"))
        {
            Console.WriteLine($"\t{hWnd:X}\t{sb}");
        }

        EnumChildWindows(hWnd, EnumAllChilds, lParam);
        return true;
    }

    static bool EnumTopLevel(IntPtr hWnd, IntPtr lParam)
    {
        StringBuilder sb = new StringBuilder(2048);

        SendMessage(hWnd, WM_GETTEXT, new IntPtr(sb.Capacity), sb);
        Console.WriteLine($"TopLevel: hWnd: {hWnd:X}\t{(string.IsNullOrEmpty($"{sb}") ? "No Caption" : $"{sb}")}");

        // Call for child windows
        EnumChildWindows(hWnd, EnumAllChilds, lParam);

        return true;
    }

    static void Main(string[] args)
    {
        // Call for TopLevel windows
        EnumWindows(EnumTopLevel, IntPtr.Zero);
        Console.ReadLine();
    }
}