【问题标题】:How to get text from CEdit control如何从 CEdit 控件中获取文本
【发布时间】:2013-01-12 13:41:11
【问题描述】:

我是 ATL 的新人。所以请原谅我问这个问题。

问题描述: 一个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);

Here 是一个关于如何从CEdit 获取文本的主题,但它不起作用。

为什么CEdit控件可以用SetWindowText()函数设置文本,但不能用GetWindowText()函数获取文本?这真的让我很困惑。如果有人可以为我解释一下,非常感谢。

【问题讨论】:

  • 我直接使用window API绕过了这个问题。使用 ::GetWindowText(m_txtInput.m_hwnd, buffer, size) 而不是直接从控件调用 GetWindowText 方法,它就可以工作了。但是我还是想知道为什么以前的方法不能通过assert。谢谢。
  • 好像 ::GetWindowText 的结果是空的...为什么?...
  • 问题成立,assert问题是由对话框关闭后调用GetInput()方法引起的。单击确定按钮后,相关窗口被释放。谢谢。

标签: c++ atl cedit


【解决方案1】:

CEdit 不是 ATL 类。命名空间ATLControls 来自哪里?有一个具有此名称的 WTL 类,从中获取文本很容易:

    ATLASSERT(Edit.IsWindow()); // Make sure the control holds a handle
    CString sWindowText;
    Edit.GetWindowText(sWindowText);

然而,GetWindowText 方法来自 ATL,并包装了 GetWindowTextLength 和 GetWindowText API。后面的 MSDN 文章也有一段代码 sn-p 展示了典型用法。

既然你提到IsWindow 对你不起作用,最可能的问题是你的编辑控件包装类变量没有真正的控件句柄,因此从无到有获取文本是不可能的。

【讨论】:

  • 一个 ATL 类被添加到我的项目中,我包含头文件 #include 以引用 ATLControls。
  • 问题解决了,对话框关闭后调用GetInput方法是我的错。之后没有窗口存在,因此 GetWindowText 不起作用。谢谢大家。 :)
  • atlcontrols.h 不是标准的 ATL 文件/类,它是某人的扩展。
  • 这些文本是从 atlcontrols.h 的头文件中复制而来的:// ATLControls.h : Helper classes for common controls // // These classes are only intended as a sample and // are NOT supported by Microsoft // // This is a part of the Active Template Library. // Copyright (C) 1996-1998 Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Active Template Library Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Active Template Library product.
  • 这是一个 10 多年前废弃的样本,而 ATL 仍然是该产品的受支持部分,信誉良好 - 请注意区别
【解决方案2】:

已经用 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; 

【讨论】:

    猜你喜欢
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 2010-10-07
    相关资源
    最近更新 更多