Knowledge Base |

# INFO: GetParent in a Dialog Box

Article ID: 118610

Article Last Modified on 11/21/2006

APPLIES TO

- Microsoft Foundation Class Library 4.2, when used with:
  - Microsoft C/C++ Professional Development System 7.0
  - Microsoft Visual C++ 1.0 Professional Edition
  - Microsoft Visual C++ 1.5 Professional Edition
  - Microsoft Visual C++ 1.51
  - Microsoft Visual C++ 1.52 Professional Edition
  - Microsoft Visual C++ 1.0 Professional Edition
  - Microsoft Visual C++ 2.0 Professional Edition
  - Microsoft Visual C++ 2.1
  - Microsoft Visual C++ 4.0 Standard Edition

This article was previously published under Q118610

## SUMMARY

The window object returned by CWnd::GetParent in a modal dialog box is the top-level window that owns the dialog box, usually the main window. It is not necessarily the window object that has been passed to the constructor or Create() of the CDialog object. If you need to access the parent window that was passed in the constructor of the dialog-box object, then you need to save a copy of this pointer in the dialog-box object.

## MORE INFORMATION

When Windows creates a new popup window or a top-level window, such as a dialog-box window, it is passed the handle of the parent window for the dialog box. If the specified parent window is not a top-level window, then Windows repeatedly calls GetParent until it finds the handle of a top-level window that contains the specified parent window. Windows then sets this top-level window to be the parent of the new popup or top-level window. So, after the new window is created, if you call GetParent in that window, you will get the pointer to the top-level window object that contains the original parent window that you passed in the constructor or Create() call.
This behavior can cause problems in an MFC application if you try to create a dialog box with a view window as the parent and then try to access the view inside the dialog box by calling GetParent. Because the view window is not a top-level window, Windows automatically converts the handle of the view window to the handle of the top-level window that contains the view, which is usually the main window of the application. Then when you call GetParent, it gets the handle of the main window of the application and then finds the MFC object associated with the main window. If you need to access the view window from the dialog-box object, then you should store the pointer to the view in a member variable of the dialog box. To do this, save a pointer to the view window in the constructor of the dialog box or override the Create() function and have it save the pointer.

Additional query words: 7.00 1.00 1.50 2.00 2.10 2.50 2.51 2.52 3.00 3.10 kbinf 4.00 kbNoUpdate

Keywords: kbinfo kbuidesign kbdlg KB118610