Reading from a text field in another application's window

Tuminoid picture Tuminoid · Dec 9, 2008 · Viewed 29.1k times · Source

Is there a way for a Windows application to access another applications data, more specifically a text input field in GUI, and grab the text there for processing in our own application?

If it is possible, is there a way to "shield" your application to prevent it?

EDIT: The three first answers seem to be about getting the another applications window title, not a specific text input field in that window.

I'm no Windows API expect, so could you be more exact how do I find a certain text field in that window, what are the prequisites for it (seems like knowing a window handle something is required, does it require knowing the text field handle as well? How do I get that? etc...)

Code snippets in C++ really would be really appreciated. MSDN help is hard to browse since Win32-API has such horrible naming conventions.

Completed! See my answer below for a how-to in C++.

Answer

Raj picture Raj · Dec 11, 2008

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

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

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.