Подтвердить что ты не робот

С# как использовать API WM_GETTEXT/GetWindowText

Я хочу получить содержимое элемента управления/дескриптора приложения.

Здесь экспериментальный код.

 Process[] processes = Process.GetProcessesByName("Notepad");
        foreach (Process p in processes)
        {
            StringBuilder sb = new StringBuilder();
            IntPtr pFoundWindow = p.MainWindowHandle;
             List <IntPtr> s =    GetChildWindows(pFoundWindow); 
            // function that returns a 
            //list of handle from child component on a given application.

             foreach (IntPtr test in s)
             {
              // Now I want something here that will return/show 
               the text on the notepad..


             }


            GetWindowText(pFoundWindow, sb,256);
            MessageBox.Show(sb.ToString()); // this shows the title.. no problem with that

        } 

любая идея? Я прочитал некоторый API-метод, например GetWindowText или WM_GETTEXT, но я не знаю, как его использовать или применять его на моем коде. Мне нужен учебник или образец кода...

Заранее спасибо:)

4b9b3361

Ответ 1

public class GetTextTestClass{

    [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    public static extern bool SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder lParam);

    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    public static extern IntPtr SendMessage(int hWnd, int Msg, int wparam, int lparam);

    const int WM_GETTEXT       = 0x000D;
    const int WM_GETTEXTLENGTH = 0x000E;

    public string GetControlText(IntPtr hWnd){

        // Get the size of the string required to hold the window title (including trailing null.) 
        Int32 titleSize = SendMessage((int)hWnd, WM_GETTEXTLENGTH, 0, 0).ToInt32();

        // If titleSize is 0, there is no title so return an empty string (or null)
        if (titleSize == 0)
            return String.Empty;

        StringBuilder title = new StringBuilder(titleSize + 1);

        SendMessage(hWnd, (int)WM_GETTEXT, title.Capacity, title);

        return title.ToString();
    }
}

Ответ 2

GetWindowText не даст вам содержимого окон редактирования из других приложений - он поддерживает только текст, управляемый по умолчанию [например, подписи меток ] через процессы для предотвращения зависаний... вам нужно будет отправить WM_GETTEXT.

Вам потребуется использовать версию SendMessage версии StringBuilder:

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

const int WM_GETTEXT = 0xD;
StringBuilder sb = new StringBuilder(65535);
// needs to be big enough for the whole text
SendMessage(hWnd_of_Notepad_Editor, WM_GETTEXT, sb.Length, sb);