I use this code to get the window name:
#include <Windows.h>
#include <stdio.h>
int main() {
TCHAR title[500];
int i=0;
while(i<10) {
GetWindowText(GetForegroundWindow(), title, 500);
printf("%s\n",title);
i++;
system("pause");
}
}
However, it gets only the foreground window.
-
I need to get all window names
-
Or, actually, I need to get one specific window name which belongs to the “notepad.exe” process.
Thanks for your help 🙂
I don’t think there’s really any easier way by using the raw winapi, but here goes:
Here’s the code I came up with:
Going through in order:
First note the wide versions of functions and strings.
TCHARis not good to use and it would be a shame if one of the titles happened to have UTF-16 in it.isNotepadjust checks the executable name member of thePROCESSENTRY32Wstructure to see whether it equals "notepad.exe". This assumes Notepad uses this process name, and that nothing that isn’t Notepad uses the process name. To eliminate false positives, you’d have to do more checking, but you can never be too sure.In
enumWindowsProc, take note thatlParamis actually a pointer to a vector of PIDs (to save ourselves from having to use a global). This constitutes the cast at the beginning of the function. Next, we get the PID of the window we found. Then, we loop through the list of PIDs passed in and check whether it matches any. If it does, I chose to grab the title and output the PID and the window title. Note that using a standard string as a buffer is only guaranteed to work in C++11, and must not have the extra null character (not part of the length) overwritten. Lastly, we returnTRUEso that it keeps enumerating until it has gone through every top-level window.Onto
main, the first thing you see is our initially empty list of PIDs. We take a snapshot of the processes and go through them. We use the helper function,isNotepadto check whether the process is "notepad.exe", and if so, store its PID. Lastly, we callEnumWindowsto enumerate the windows, and pass in the list of PIDs, disguised as the requiredLPARAM.It’s a bit tricky if you haven’t done this sort of thing, but I hope it makes sense. If you want the child windows, the correct thing to do would be to add a
EnumChildWindowsProcand callEnumChildWindowswith that in the spot where I output information about the found window. If I’m correct, you don’t need to recursively callEnumChildWindowsto get grandchildren etc., as they will be included in the first call.