如何将 CEdit 类型的数据转换为 CString 类型的数据,以及如何在消息框中显示?

How to convert CEdit type of data in to CString type data and how to display that in a messagebox?

我想知道CEdit(用户输入)的数据如何显示在消息框上。

我想接受用户的输入并需要在 messagebox.Simple 中显示它,但我无法将 CEdit 类型(用户输入)转换为 CString 类型(我必须在其中显示消息框)。

这是我的代码片段

In .h file
    CEdit* pEdit = new CEdit;
    CString text;

In .cpp file
    pEdit.Create(WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER,
                CRect(150, 10, 500, 50), this, 1);
    pEdit.GetWindowText(text);

有两种方法可以做到这一点。

您可以将编辑控件绑定到 CString 变量。当你想要获取文本数据时,调用 UpdateData(TRUE) 并且 CString 变量存储了文本数据。

也可以像下面这样工作:

CString textStr;
CEdit* pEdit = new CEdit;
//call when you want get text
pEdit ->GetWindowText(textStr);

因为您已经以编程方式创建了文本框。

编辑:
在头文件

中声明 CEdit
CEdit* pEdit;

OnInitdialog()函数中写入这段代码

pEdit = new CEdit; 
pEdit->Create(WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER,CRect(150, 10, 500, 50), this, 1); 

现在单击任何按钮都可以显示消息框。例如

OnButtonOk()
{
    CString strText;
    pEdit->GetWindowText(strText);
    AfxMessageBox(strText);
}

documentation for CEdit 明确指出:

To set and retrieve text from a CEdit object, use the CWnd member functions SetWindowText and GetWindowText, which set or get the entire contents of an edit control, even if it is a multiline control.

鉴于您创建了 CEdit 对象,

CString strOut;
pEdit->GetWindowText(strOut);

CWnd::GetWindowText