C++ MFC how to use GetDlgItem()

2019-08-10 21:22发布

问题:

This is in the main "example dlg.cpp" file:

void CHelixV3Dlg::OnBnClickedCancel()
{
   CEdit* editbox = (CEdit*)GetDlgItem(IDC_EDIT1); 
  //works fine, defined as: *CWnd GetDlgItem(int nID); in this file
}

This is test.cpp source file

void test()
{
   CEdit* editbox = (CEdit*)GetDlgItem(IDC_EDIT1);
   //does not work at all, seems to be a winAPI function instead of MFC...
   //defined as: HWND __stdcall GetDlgItem(HWND hDlg, int nIDDlgItem);
}

both source files are in the same project, use the same headers, but test()'s GetDlgItem is obviously a Win32 API function, which does not work in MFC... How could I get GetDlgItem() working in the test.cpp file?

回答1:

You don't understand C++ scoping rules.

In your first usage, you end up calling CWnd::GetDlgItem() because you are making your call from CHelixV3Dlg. Your dialog class is derived from CDialog which is derived from CWnd. Using normal C++ scoping rules, if there is a member function that has GetDlgItem as its name, it will be the one to be used.

In your second usage, you end up calling GetDlgItem() as defined in the WINAPI headers. That is because CWnd::GetDlgItem() is not in your scope.

If you want to call the CWnd version in your second usage, somehow you will have to get a pointer or reference to an instance of CHelixV3Dlg that has been created and has a valid HWND. Once you have that pointer:

void test(CHelixV3Dlg* pDlg)
{
   CEdit* editbox = (CEdit*)pDlg->GetDlgItem(IDC_EDIT1);
   // do some stuff with editbox...
}


回答2:

The MFC version of GetDlgItem uses the HWND of the class making the call. In your CHelixV3Dlg example it is using the dialog HWND and accessing a child control of that window. This function is only for accessing child windows.



标签: c++ winapi mfc