如何将在编辑框中键入的值分配给 MFC 中的变量
How to assign a value typed in edit box to a variable in MFC
在我用来编程的任何其他语言中,您都可以使用此代码为变量赋值
String x;
Edit1->Text = x;
//or
x = Edit1->Text;
这就是它在 c++builder 中的做法,我怎么能在 MFC 中这样做呢?
这取决于您如何定义编辑控件。编辑控件可以定义为包含 CString 值或实际的 CEdit 控件。
因此,如果您将其定义为 CString,则可以使用类似...
std::string str;
str = m_edit; // m_edit is edit field on dialog defined to use CString
或者,如果将其用作对照...
CString str2;
m_edit.GetWindowText(str2); // m_edit is edit field defined as CEdit control.
str = str2;
注意:您需要使用 UpdateData 函数(或等效函数)将字符串从编辑字段传输到局部变量。
你可以试试这个代码
CString x;
m_edit.GetWindowText(x); // to Get editbox text
x = _T("Hello World");
m_edit.SetWindowText(x); // to Set editbox text
这里m_edit
是editbox的变量
CYourClass::DoDataExchange(CDataExchange* pDX)
{
CBaseClass::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1, m_strEdit);
}
UpdateData(TRUE)
将文本从对话框/视图复制到变量 m_strEdit,UpdateData(FALSE)
将文本从该变量复制到对话框。每次调用此函数时,框架都会调用 CYourClass::DoDataExchange
。
CBaseClass
是 MFC class 您的 class 派生自(CView
、CWnd
、CDialog
等)。 IDC_EDIT1
是在 resource.h 中定义的控件 ID,并在您的对话框资源文件中使用。
m_strEdit
是类型 CString
在我用来编程的任何其他语言中,您都可以使用此代码为变量赋值
String x;
Edit1->Text = x;
//or
x = Edit1->Text;
这就是它在 c++builder 中的做法,我怎么能在 MFC 中这样做呢?
这取决于您如何定义编辑控件。编辑控件可以定义为包含 CString 值或实际的 CEdit 控件。
因此,如果您将其定义为 CString,则可以使用类似...
std::string str;
str = m_edit; // m_edit is edit field on dialog defined to use CString
或者,如果将其用作对照...
CString str2;
m_edit.GetWindowText(str2); // m_edit is edit field defined as CEdit control.
str = str2;
注意:您需要使用 UpdateData 函数(或等效函数)将字符串从编辑字段传输到局部变量。
你可以试试这个代码
CString x;
m_edit.GetWindowText(x); // to Get editbox text
x = _T("Hello World");
m_edit.SetWindowText(x); // to Set editbox text
这里m_edit
是editbox的变量
CYourClass::DoDataExchange(CDataExchange* pDX)
{
CBaseClass::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1, m_strEdit);
}
UpdateData(TRUE)
将文本从对话框/视图复制到变量 m_strEdit,UpdateData(FALSE)
将文本从该变量复制到对话框。每次调用此函数时,框架都会调用 CYourClass::DoDataExchange
。
CBaseClass
是 MFC class 您的 class 派生自(CView
、CWnd
、CDialog
等)。 IDC_EDIT1
是在 resource.h 中定义的控件 ID,并在您的对话框资源文件中使用。
m_strEdit
是类型 CString