我是从CEdit派生的,以创建一个自定义控件。如果像MFC控件(Mask,Browsable)一样,我可以更改GetWindowText来实际报告控件上通常显示的内容(例如,在十六进制和十进制之间转换数据,然后返回该字符串),那就太好了。
这在派生的CEdit中是可能的吗?
发布于 2017-10-27 10:26:07
将WM_GETTEXT和WM_GETTEXTLENGTH的消息映射项添加到派生的CEdit类中:
BEGIN_MESSAGE_MAP( CMyEdit, CEdit )
ON_WM_GETTEXT()
ON_WM_GETTEXTLENGTH()
END_MESSAGE_MAP()在重写这些消息时,我们需要一种方法来获取编辑控件的原始文本,而不需要进行无休止的递归。为此,我们可以直接调用名为DefWindowProc的默认窗口过程。
CStringW CMyEdit::GetTextInternal()
{
CStringW text;
LRESULT len = DefWindowProcW( WM_GETTEXTLENGTH, 0, 0 );
if( len > 0 )
{
// WPARAM = len + 1 because the length must include the null terminator.
len = DefWindowProcW( WM_GETTEXT, len + 1, reinterpret_cast<LPARAM>( text.GetBuffer( len ) ) );
text.ReleaseBuffer( len );
}
return text;
}下面的方法获取原始窗口文本并对其进行转换。任何事情在这里都是可能的,包括在十六进制和十二月之间转换的例子。为了简单起见,我只是把文本用破折号括起来。
CStringW CMyEdit::GetTransformedText()
{
CStringW text = GetTextInternal();
return L"--" + text + L"--";
}现在是WM_GETTEXT的实际处理程序,它将转换后的文本复制到输出缓冲区。
int CMyEdit::OnGetText( int cchDest, LPWSTR pDest )
{
// Sanity checks
if( cchDest <= 0 || ! pDest )
return 0;
CStringW text = GetTransformedText();
// Using StringCchCopyExW() to make sure that we don't write outside of the bounds of the pDest buffer.
// cchDest defines the maximum number of characters to be copied, including the terminating null character.
LPWSTR pDestEnd = nullptr;
HRESULT hr = StringCchCopyExW( pDest, cchDest, text.GetString(), &pDestEnd, nullptr, 0 );
// If our text is greater in length than cchDest - 1, the function will truncate the text and
// return STRSAFE_E_INSUFFICIENT_BUFFER.
if( SUCCEEDED( hr ) || hr == STRSAFE_E_INSUFFICIENT_BUFFER )
{
// The return value is the number of characters copied, not including the terminating null character.
return pDestEnd - pDest;
}
return 0;
}WM_GETTEXTLENGTH的处理程序是不言自明的:
UINT CMyEdit::OnGetTextLength()
{
return GetTransformedText().GetLength();
}发布于 2017-10-27 13:03:20
感谢大家为我指明了正确的方向。我尝试了OnGetText,但问题似乎是我无法获得底层字符串,否则它在调用GetWindowText时会崩溃(或者只是调用OnGetText again...and找不到底层字符串)。
在看到他们在蒙面控制下所做的事情之后,我做了一个简单的回答,就像这样。有什么缺点吗?似乎不会引起任何问题或副作用..。
直接从GetWindowText派生
void CConvertibleEdit::GetWindowText(CString& strString) const
{
CEdit::GetWindowText(strString);
ConvertibleDataType targetDataType;
if (currentDataType == inputType)
{
}
else
{
strString = ConvertEditType(strString, currentDataType, inputType);
}
}https://stackoverflow.com/questions/46964320
复制相似问题