且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从另一个应用程序窗口中的文本字段读取

更新时间:2023-11-03 18:42:16

要从另一个应用程序的文本框中读取文本内容,您需要以某种方式获取该文本框控件的窗口句柄。根据应用程序UI的设计方式(如果它有一个UI),有几种不同的方法可以用来获取此句柄。你可以使用FindWindow/FindWindowEx找到你的控件或使用WindowFromPoint,如果这是有道理的。无论如何,一旦你有了文本控件的句柄,你可以发送一个WM_GETTEXT消息来检索它的内容(假设它是一个标准的文本框控件)。这是一个精心编写的示例(无错误检查):

For reading text content from another application's text box you will need to get that text box control's window handle somehow. Depending on how your application UI is designed (if it has a UI that is) there are a couple of different ways that you can use to get this handle. You might use "FindWindow"/"FindWindowEx" to locate your control or use "WindowFromPoint" if that makes sense. Either way, once you have the handle to the text control you can send a "WM_GETTEXT" message to it to retrieve its contents (assuming it is a standard text box control). Here's a concocted sample (sans error checks):

HWND hwnd = (HWND)0x00310E3A;
char szBuf[2048];
LONG lResult;

lResult = SendMessage( hwnd, WM_GETTEXT, sizeof( szBuf ) / sizeof( szBuf[0] ), (LPARAM)szBuf );
printf( "Copied %d characters.  Contents: %s\n", lResult, szBuf );

我使用Spy ++获取一个文本框窗口的句柄。

I used "Spy++" to get the handle to a text box window that happened to be lying around.

为了保护自己的文本框不被这样检查,你可以总是子类化你的文本框(参见SetWindowLong用GWL_WNDPROC为nIndex 参数),并对WM_GETTEXT消息进行一些特殊处理,以确保只有来自同一进程的请求得到服务。

As for protecting your own text boxes from being inspected like this, you could always sub-class your text box (see "SetWindowLong" with "GWL_WNDPROC" for the "nIndex" parameter) and do some special processing of the "WM_GETTEXT" message to ensure that only requests from the same process are serviced.