15,980
社区成员
发帖
与我相关
我的任务
分享
#pragma once
class CMyRichEditCtrl : public CRichEditCtrl
{
public:
CMyRichEditCtrl();
~CMyRichEditCtrl();
DECLARE_DYNAMIC(CMyRichEditCtrl)
DECLARE_MESSAGE_MAP()
public:
void AppendText(CString strText); // 追加文本
protected:
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
void _AppendText(CString strText);
private:
CString m_strTextForAppend; // 要追加的文本
BOOL m_bLButtonDown; // 鼠标左键被按下
};
MyRichEdit.cpp
#include "stdafx.h"
#include "MyRichEdit.h"
IMPLEMENT_DYNAMIC(CMyRichEditCtrl, CRichEditCtrl)
CMyRichEditCtrl::CMyRichEditCtrl()
{
m_strTextForAppend = "";
m_bLButtonDown = FALSE;
}
CMyRichEditCtrl::~CMyRichEditCtrl()
{
}
BEGIN_MESSAGE_MAP(CMyRichEditCtrl, CRichEditCtrl)
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
END_MESSAGE_MAP()
void CMyRichEditCtrl::AppendText(CString strText)
{
if (m_bLButtonDown)
{
// 迂回策略,在选择时不再追加
m_strTextForAppend += strText;
}
else
{
_AppendText(strText);
}
}
void CMyRichEditCtrl::OnLButtonDown(UINT nFlags, CPoint point)
{
m_bLButtonDown = TRUE;
CRichEditCtrl::OnLButtonDown(nFlags, point);
}
void CMyRichEditCtrl::OnLButtonUp(UINT nFlags, CPoint point)
{
m_bLButtonDown = FALSE;
_AppendText(m_strTextForAppend); // 追加
m_strTextForAppend.Empty();
CRichEditCtrl::OnLButtonUp(nFlags, point);
}
void CMyRichEditCtrl::_AppendText(CString strText)
{
long lBegin = -1;
long lEnd = -1;
this->SetRedraw(FALSE); // 设置不更新
this->HideSelection(FALSE, TRUE);
this->GetSel(lBegin, lEnd);
int iLine = this->GetFirstVisibleLine();
this->SetSel(-1, -1);
this->ReplaceSel(strText);
int iLineCount = this->GetLineCount();
this->LineScroll(-iLineCount); // 滚动到最顶部
this->LineScroll(iLine); // 滚回之前显示的行
this->SetSel(lBegin, lEnd);
this->HideSelection(TRUE, TRUE);
this->SetRedraw(TRUE); // 设置更新
this->Invalidate(FALSE); // 刷新
}
首先,追加的时候设置不更新,但要注意的是,SetRedraw(FALSE)后,被控件挡住的其他控件可能会被刷出来,所以要注意把被挡住的控件隐藏或移走。追加完了,在设置更新,并调用刷新,其不会自动更新。
其次,选择文本的时候,会被追加的操作中断,参考幻梦的意见,选择文本的时候不追加,选择完再追加,没有去找更好的方法。
再次,RichEdit用的是1.0,不能用2.0版本,否则在输入时,输入法的输入框会被追加的操作打断。
感谢赵老师,虽然没有用自绘的方法,但自绘效果应该会更好。其次感谢zgl7903,虽然他的方法没有直接解决我的问题,但也间接的让我找到解决的思路,最后是幻夢之葉,提供了一个很好的方法。
现在ok了,可能还有小问题,但影响不大,容易解决。留下解决的方法,让其他人可以借鉴。
richEditCtrl->SetFocus();
richEditCtrl->SetSel(-1, -1);
richEditCtrl->HideSelection(FALSE, TRUE);
richEditCtrl->ReplaceSel(szlog);
richEditCtrl->HideSelection(TRUE, TRUE);