This question already has an answer here:
I'm looking for the best way to get a Window Handle in the following situation:
I have the process id and process handle, I know the window titlename and I know that the process has only one window.
So how would I do it? FindWindow
? EnumWIndows
?
Using
FindWindow
requires that you either know the window class or the window title. Both of these are not necessarily unique. Since you alread have the process handle (and its ID) you can implement a robust solution usingEnumWindows
.First, declare a structure used for communication. It passes a process ID to the enumeration procedure and returns the window handle back.
Next, we need a callback procedure that retrieves the process ID (
GetWindowThreadProcessId
) for any given window and compares it to the one we are looking for:What's left is the public interface. It populates the structure used for communication with the process ID, triggers the enumeration of top-level windows, and returns the window handle. The calls to
SetLastError
andGetLastError
are required, sinceEnumWindows
returnsFALSE
for both error and success in this case:This will retrieve the first top-level window that matches a given process ID. Since the requirements state that there will only ever be a single window for the given process, the first one that matches is the correct window.
If additional restrictions exist,
EnumProc
can be expanded to include those. I have marked the spot in the implementation above, where additional filters can be applied.