C++ 如何从 CEdit 控件获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14575228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get text from CEdit control
提问by Erxin
I'm a new guy with ATL. So forgive me to ask this question.
我是 ATL 的新人。所以请原谅我提出这个问题。
Problem description:One CEdit control is added into a ATL dialog class. It's attached in the dialog initialize function.
问题描述:一个CEdit控件被添加到一个ATL对话框类中。它附加在对话框初始化函数中。
//Define the edit control
ATLControls::CEdit m_txtInput;
//In the OnInitDialog function
m_txtInput.Attach(GetDlgItem(IDC_INPUT_LINE));
m_txtInput.SetWindowText(_T("New directory"));
//In the public memeber function of the dialog GetInput()
//I have tried three kinds of method to get the text. But all of them are throw an
//assert exception, IsWindow() failed.
//1.
GetDlgItemText(IDC_INPUT_LINE, input);
//2.
ZeroMemory(m_lptstrInput, MAX_PATH);
m_txtInput.GetLine(0, m_lptstrInput, MAX_PATH);
//3.
BSTR input;
m_txtInput.GetWindowText(input);
Hereis a topic about how to get text from CEdit but it is not working.
这是一个关于如何从 CEdit 获取文本但它不起作用的主题。
Why the CEdit control could be set text with the function SetWindowText() but can't get the text by the function GetWindowText()? It's really confuse me. Thanks a lot if someone could explain it for me.
为什么 CEdit 控件可以使用函数 SetWindowText() 设置文本,但不能通过函数 GetWindowText() 获取文本?这真的让我很困惑。如果有人可以为我解释一下,非常感谢。
回答by Roman R.
CEdit
is not an ATL class. Where the namespace ATLControls
comes from? There is a WTL class with this name and getting text from it is easy:
CEdit
不是 ATL 类。命名空间ATLControls
从何而来?有一个具有此名称的 WTL 类,从中获取文本很容易:
ATLASSERT(Edit.IsWindow()); // Make sure the control holds a handle
CString sWindowText;
Edit.GetWindowText(sWindowText);
The method GetWindowText
is coming from ATL however and wraps GetWindowTextLength
and GetWindowText
API. The latter MSDN article also has a code snippet showing typical usage.
GetWindowText
然而,该方法来自 ATL 并包装GetWindowTextLength
和GetWindowText
API。后一篇 MSDN 文章也有一个代码片段显示了典型用法。
Since you mention that IsWindow
does not work for you, the most likely problem is that your edit control wrapper class variable just does not have a handle of a real control, and hence getting text from nothing is impossible.
由于您提到这IsWindow
对您不起作用,因此最可能的问题是您的编辑控件包装类变量没有实际控件的句柄,因此不可能从无到有获取文本。
回答by sg7
This has been tested with MFC & VS2015:
这已经用 MFC & VS2015 测试过:
//
// Get char string/CString from CEdit m_ceDate;
// where
// DDX_Control(pDX, IDC_EDIT_DATE, m_ceDate);
char cdateBuf[128];
UINT nCountOfCharacters = GetDlgItemText(IDC_EDIT_DATE, cdateBuf, 16);
CString csDate = cdateBuf;