golosovsky
golosovsky

Reputation: 718

winapi - a standard way to retrieve text from running text editor

Is there a standard message that can be sent to a text editor window or a certain WinApi call, that will retrieve the contents of the currently edited text?

For example, to retrieve the current contents of a Notepad window. (assumed that the most up to date text wasn't yet written to a file)

I've tried retrieving the text via SendMessage using WM_GETTEXTWM_GETTEXTLENGTH but I was able to retrieve the title text only.

Upvotes: 2

Views: 725

Answers (1)

rustyx
rustyx

Reputation: 85461

In general no there is no standard message for this.

But Windows' Notepad has an "Edit" child which responds to WM_GETTEXT and WM_GETTEXTLENGTH - messages normally used to retrieve text from input controls.

Here's a PoC demonstrating the idea:

#include <iostream>
#include <vector>
#include <string.h>
#include <Windows.h>

BOOL CALLBACK enumProc(HWND hwnd, LPARAM) {
    std::vector<char> buf(100);
    GetClassNameA(hwnd, buf.data(), 100);
    if (strcmp(buf.data(), "Notepad")) return TRUE;
    hwnd = FindWindowEx(hwnd, NULL, "Edit", NULL);
    if (!hwnd) return TRUE;
    int textLength = SendMessageA(hwnd, WM_GETTEXTLENGTH, 0, 0) + 1;
    if (textLength <= 0) return TRUE;
    buf.resize(textLength);
    SendMessage(hwnd, WM_GETTEXT, textLength, (LPARAM)buf.data());
    std::cout << buf.data() << "\n";
    return TRUE;
}

int main() {
    EnumWindows(&enumProc, 0);
}

Works on Windows 10:

retrieve text from running notepad winapi

Upvotes: 3

Related Questions