2
votes

I'm using the following code inside a global CBT hook procedure:

TCHAR title[256];
int getT = GetWindowText(hWnd, title, 256);
if (getT == 0) {
    int err = GetLastError();
    logFile << "Error GetWindowText(): " << err << endl;
} else {
    logFile << "getT = " << getT << endl;
}

The problem is that for certain windows the GetWindowText() function works just fine and I get the correct window title, but for some others it returns 0 and I get an empty string. The GetLastError() returns 183 which is ERROR_ALREADY_EXISTS:

Cannot create a file when that file already exists.

The error is not random: I always get it with the same kind of window opened by the same application, but for all the other windows it seems to work fine.

1
Are you attempting to retrieve the text of an edit control in another application? - Mike Kwan
No, I'm trying to get the title of a window - The Coding Monk
Is this a window we will have on our systems that we can test against? - Mike Kwan
Try to call SetLastError(666) before calling GetWindowText. If you will start getting 666 back, it may mean GetWindowText is intercepted with an api hook which prevents reading a certain window and doesn't bother setting a proper error code. - hamstergene
Maybe their table windows is an edit control, just modified enough to appear as a regular window. Or it might be just mimicing a real window and not using SetWindowText() at all. What does Spy++ tell you about the window? - RedX

1 Answers

1
votes

You might not have the rights to retrieve text from certain windows on Windows Vista and above.

My guess is that ERROR_ALREADY_EXISTS comes from your log file when you print "Error GetWindowText(): ". You should get the error code first before doing anything else.

Another possibility is that the window returns 0 from its WM_GETTEXT handler without setting the last error. As GetWindowText documentation states, if you call it on a window belonging to the same process, it retrieves the text by sending this message. Since you are calling the function from a hook, you might be in the same process.