MFC跨文件获取编辑框资源ID及调用控件内容的问题求助
Hey there! Let's work through this MFC snag you're hitting—totally normal for new folks, so no stress. Let's break down what's off with your current code and walk through the fix step by step.
First, Let's Diagnose Your Code Issues
You've got two main missteps right now:
- You're misusing the
GetDlgItemTextWfunction with your control variable - You're trying to access the resource ID like it's a member of the dialog class (it's not!)
Step 1: Include the Required Headers
First up, in your MyNew.cpp file, you need to include the headers that define your main dialog class and the resource IDs. Add these at the top:
#include "MainMFCDlg.h" #include "Resource.h" // This defines IDC_MYEDIT_EDIT; skip if MainMFCDlg.h already includes it
Without these, the compiler won't recognize CMainMFCDlg or IDC_MYEDIT_EDIT at all.
Step 2: Fix the Control Access Code
You have two simple, valid ways to get the edit control's text—both way cleaner than what you tried:
Method 1: Use the Associated Control Variable
Since you already linked m_myEdit_Edit to IDC_MYEDIT_EDIT, you can call GetWindowTextW directly on this variable—no need to pass the resource ID at all:
// Get main dialog pointer with a safety check (critical to avoid crashes!) CMainMFCDlg* pMainDlg = dynamic_cast<CMainMFCDlg*>(AfxGetMainWnd()); if (pMainDlg == nullptr) { // Handle the case where we can't access the main window (e.g., log an error) return; } CString myString; // Grab text directly from the linked control variable pMainDlg->m_myEdit_Edit.GetWindowTextW(myString);
Method 2: Use the Dialog's GetDlgItemTextW
If you want to use the resource ID directly (without the control variable), call the function on the dialog object instead of the control variable:
CMainMFCDlg* pMainDlg = dynamic_cast<CMainMFCDlg*>(AfxGetMainWnd()); if (pMainDlg == nullptr) { return; } CString myString; // Use the dialog's own GetDlgItemText with the resource ID pMainDlg->GetDlgItemTextW(IDC_MYEDIT_EDIT, myString);
Why Your Original Code Failed
MainMFCDlg->m_myEdit_Edit.GetDlgItemTextW(*IDC_MYEDIT_EDIT*, myString): TheGetDlgItemTextfunction on a control variable is meant to fetch text from a child control of that control, not the control itself. Also,IDC_MYEDIT_EDITis a numeric macro—you don't need to dereference it with*.MainDlg->IDC_MYEDIT_EDIT:IDC_MYEDIT_EDITis a global resource ID defined inResource.h, not a member of theCMainMFCDlgclass. You can't access it through the dialog object like that.
Bonus: Always Check for Valid Pointers
Adding the nullptr check for pMainDlg prevents crashes if the main window isn't available for some reason—this is a good habit to get into with MFC!
内容的提问来源于stack exchange,提问作者ngmany

