CRichEditCtrl阻止在SetSet上自动滚动

CRichEditCtrl prevent auto scroll on SetSel

本文关键字:滚动 SetSet CRichEditCtrl      更新时间:2023-10-16

我有一个继承自CRichEditCtrl的CMyRichEditCtrl类。当我调用SetSel时,它会自动滚动CRichEditCtrl的内容,以便插入符号可见。我想避免这种行为。

困扰我的是,这种行为似乎在6.0和其他版本之间发生了变化。

Visual Studio 2010:http://msdn.microsoft.com/en-us/library/4zek9k1f(v=vs.100).aspx

插入符号放置在由开始(cpMin或nStartChar)和结束(cpMax或nEndChar)索引中较大者指示的选择的末尾此函数滚动CRichEditCtrl的内容,以便插入符号可见

Visual Studio 6.0:http://msdn.microsoft.com/en-us/library/aa313352(v=vs.60).aspx

插入符号放置在由开始(cpMin或nStartChar)和结束(cpMax或nEndChar)索引中较大者指示的选择的末尾此函数不会滚动CRichEditCtrl的内容以使插入符号可见

调用SetSel时,有没有办法防止控件自动滚动?

这不是一个容易的过程,但我终于找到了一个解决方法。

void CMyRichEditCtrl::doStuff()
{
    SetRedraw( FALSE );
    int nOldFirstVisibleLine = GetFirstVisibleLine();
    // Save current selection
    long lMinSel, lMaxSel;
    GetSel( lMinSel, lMaxSel );
    // Do something here
    doSomething();
    // Restore selection
    SetSel( lMinSel, lMaxSel );
    // Prevent the auto-scroll of the control when calling SetSel()
    int nNewFirstVisibleLine = GetFirstVisibleLine();
    if( nOldFirstVisibleLine != nNewFirstVisibleLine )
        LineScroll( nOldFirstVisibleLine - nNewFirstVisibleLine );
    SetRedraw( TRUE );
    RedrawWindow();
 }

使用CRichEditCtrl::SetOptions方法或以下代码禁用和启用自动滚动。hwnd是富编辑控件的句柄。

您可以使用以下代码禁用自动滚动:

LRESULT prevOptions = SendMessage(hwnd, EM_GETOPTIONS, 0, 0);
SendMessage(hwnd, EM_SETOPTIONS, ECOOP_SET, prevOptions & ~ECO_AUTOVSCROLL);

并使用启用它

SendMessage(hwnd, EM_SETOPTIONS, ECOOP_SET, prevOptions);

更改为

重新绘制窗口(0,0,RDW_NOERASE);

它更好。