Home > database >  get all text written inside a window
get all text written inside a window

Time:02-28

I want to get all text of a window.

I prepared below code.But i can only get window captions/titles.

How can i get all text written inside a 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);
            }
        }

CodePudding user response:

You need to enumerate all child windows of the top level windows. You can use EnumChildWindows API in order to accomplish that.

Here is the sample code i have written in C# for you

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

Notepad

  • Related