Windows find window class
Функция FindWindow извлекает дескриптор окна верхнего уровня, имя класса и имя окна которого соответствуют заданным строкам. Эта функция не ищет дочерние окна. Эта функция не выполняет регистрозависимый поиск.
Чтобы найти дочерние окна, начинающиеся с заданного дочернего окна, используют функцию FindWindowEx
LPCTSTR lpClassName, // указатель на имя класса
LPCTSTR lpWindowName // указатель на имя окна
[in]Указатель на строку с нулевым символом в конце, которая определяет имя класса или класс атома, который создается предварительным вызовом функции RegisterClass или RegisterClassEx . Идентифицирует строку имени класса. Атом младшим словом параметра lpClassName ; старшее слово должно быть нулевое.
Если параметр lpClassName указывает на строку, он устанавливает имя класса окна. Имя класса может быть любое имя, зарегистрированное функцией RegisterClass или RegisterClassEx , или любым из предопределенных имен классов органов управления .
[in] Указывает на строку с нулевым символом в конце, которая определяет имя окна (заголовок окна). Если этот параметр — ПУСТО (NULL), соответствуют имена всех окон.
Если функция завершилась успешно, возвращаемое значение — дескриптор окна, которое имеет заданное имя класса и имя окна.
Если функция завершается ошибкой, возвращаемое значение — ПУСТО (NULL). Чтобы получить дополнительные данные об ошибках, вызовите функцию GetLastError .
Если параметр lpWindowName не является значением ПУСТО (NULL), функция FindWindow вызывает функцию GetWindowText , чтобы извлечь имя окна для сравнения. За описанием потенциальной проблемы, которая может возникать при этом, см. Замечания в статье GetWindowText .
FindWindowW function (winuser.h)
Retrieves a handle to the top-level window whose class name and window name match the specified strings. This function does not search child windows. This function does not perform a case-sensitive search.
To search child windows, beginning with a specified child window, use the FindWindowEx function.
Syntax
Parameters
The class name or a class atom created by a previous call to the RegisterClass or RegisterClassEx function. The atom must be in the low-order word of lpClassName; the high-order word must be zero.
If lpClassName points to a string, it specifies the window class name. The class name can be any name registered with RegisterClass or RegisterClassEx, or any of the predefined control-class names.
If lpClassName is NULL, it finds any window whose title matches the lpWindowName parameter.
The window name (the window’s title). If this parameter is NULL, all window names match.
Return value
If the function succeeds, the return value is a handle to the window that has the specified class name and window name.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Remarks
If the lpWindowName parameter is not NULL, FindWindow calls the GetWindowText function to retrieve the window name for comparison. For a description of a potential problem that can arise, see the Remarks for GetWindowText.
Examples
The winuser.h header defines FindWindow as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.
FindWindowA function (winuser.h)
Retrieves a handle to the top-level window whose class name and window name match the specified strings. This function does not search child windows. This function does not perform a case-sensitive search.
To search child windows, beginning with a specified child window, use the FindWindowEx function.
Syntax
Parameters
The class name or a class atom created by a previous call to the RegisterClass or RegisterClassEx function. The atom must be in the low-order word of lpClassName; the high-order word must be zero.
If lpClassName points to a string, it specifies the window class name. The class name can be any name registered with RegisterClass or RegisterClassEx, or any of the predefined control-class names.
If lpClassName is NULL, it finds any window whose title matches the lpWindowName parameter.
The window name (the window’s title). If this parameter is NULL, all window names match.
Return value
If the function succeeds, the return value is a handle to the window that has the specified class name and window name.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Remarks
If the lpWindowName parameter is not NULL, FindWindow calls the GetWindowText function to retrieve the window name for comparison. For a description of a potential problem that can arise, see the Remarks for GetWindowText.
Examples
The winuser.h header defines FindWindow as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.
FindWindowExA function (winuser.h)
Retrieves a handle to a window whose class name and window name match the specified strings. The function searches child windows, beginning with the one following the specified child window. This function does not perform a case-sensitive search.
Syntax
Parameters
A handle to the parent window whose child windows are to be searched.
If hwndParent is NULL, the function uses the desktop window as the parent window. The function searches among windows that are child windows of the desktop.
If hwndParent is HWND_MESSAGE, the function searches all message-only windows.
A handle to a child window. The search begins with the next child window in the Z order. The child window must be a direct child window of hwndParent, not just a descendant window.
If hwndChildAfter is NULL, the search begins with the first child window of hwndParent.
Note that if both hwndParent and hwndChildAfter are NULL, the function searches all top-level and message-only windows.
The class name or a class atom created by a previous call to the RegisterClass or RegisterClassEx function. The atom must be placed in the low-order word of lpszClass; the high-order word must be zero.
If lpszClass is a string, it specifies the window class name. The class name can be any name registered with RegisterClass or RegisterClassEx, or any of the predefined control-class names, or it can be MAKEINTATOM(0x8000) . In this latter case, 0x8000 is the atom for a menu class. For more information, see the Remarks section of this topic.
The window name (the window’s title). If this parameter is NULL, all window names match.
Return value
If the function succeeds, the return value is a handle to the window that has the specified class and window names.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Remarks
The FindWindowEx function searches only direct child windows. It does not search other descendants.
If the lpszWindow parameter is not NULL, FindWindowEx calls the GetWindowText function to retrieve the window name for comparison. For a description of a potential problem that can arise, see the Remarks section of GetWindowText.
An application can call this function in the following way.
FindWindowEx( NULL, NULL, MAKEINTATOM(0x8000), NULL );
Note that 0x8000 is the atom for a menu class. When an application calls this function, the function checks whether a context menu is being displayed that the application created.
The winuser.h header defines FindWindowEx as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.
FindWindow by class name not working?
To preface we have a strange requirement that all dialogs must be modeless for an MFC application. There is a particular dialog using region drawing and some custom controls to select dates and times for viewing past and future data per view. I need to be able to close this window when it loses focus, the main app gets a system command, etc.
I figured the easiest way to do this would be to register the class like so:
Then later in response to various event handlers and messages where I would want these modeless window or windows to be closed to do something simple like this:
However despite the registration of the class succeeding and looking at GetRuntimeClass of the dialog in question in debug and seeing that is matches up as expected the FindWindow never seems to find or close these modeless dialogs as expected.
What am I doing wrong or is there a better way to go about this?
Update: This is how the dialog is created via a static method on the dialog class. The dialog resource for the id specified in create has the Popup property set which should resolve to WS_POPUP style under the MFC covers. The dialog shouldn’t and doesn’t have a parent as far as I knew.
Update: Doh! FindWindowEx isn’t finding anything either.
However I have a new plan. I’m just going to make my own window message and handle it on the main frame. I think I can get away with passing a pointer to the dialog as the lParam of the message and then casting it to a CWnd* then calling DestroyWindow . It will work for most cases in a very round about way. I may run into trouble with minimizing and maximizing of the main frame window for dialogs that nothing is holding a pointer too but we’ll see.