c# – 如何在不滚动和丢失选择的情况下将文本附加到RichTextBox?

我需要将文本附加到RichTextBox,并且需要在不使文本框滚动或丢失当前文本选择的情况下执行它,是否可能?

解决方法

当您使用文本和选择文本方法时,WinForms中的RichTextBox非常快乐.

我有一个标准的替代品,用以下代码关闭绘画和滚动:

class RichTextBoxEx: RichTextBox
{
  [DllImport("user32.dll")]
  static extern IntPtr SendMessage(IntPtr hWnd,Int32 wMsg,Int32 wParam,ref Point lParam);

  [DllImport("user32.dll")]
  static extern IntPtr SendMessage(IntPtr hWnd,IntPtr lParam);

  const int WM_USER = 0x400;
  const int WM_SETREDRAW = 0x000B;
  const int EM_GETEVENTMASK = WM_USER + 59;
  const int EM_SETEVENTMASK = WM_USER + 69;
  const int EM_GETSCROLLPOS = WM_USER + 221;
  const int EM_SETSCROLLPOS = WM_USER + 222;

  Point _ScrollPoint;
  bool _Painting = true;
  IntPtr _EventMask;
  int _Suspendindex = 0;
  int _SuspendLength = 0;

  public void SuspendPainting()
  {
    if (_Painting)
    {
      _Suspendindex = this.SelectionStart;
      _SuspendLength = this.SelectionLength;
      SendMessage(this.Handle,EM_GETSCROLLPOS,ref _ScrollPoint);
      SendMessage(this.Handle,WM_SETREDRAW,IntPtr.Zero);
      _EventMask = SendMessage(this.Handle,EM_GETEVENTMASK,IntPtr.Zero);
      _Painting = false;
    }
  }

  public void ResumePainting()
  {
    if (!_Painting)
    {
      this.Select(_Suspendindex,_SuspendLength);
      SendMessage(this.Handle,EM_SETSCROLLPOS,EM_SETEVENTMASK,_EventMask);
      SendMessage(this.Handle,1,IntPtr.Zero);
      _Painting = true;
      this.Invalidate();
    }
  }
}

然后从我的形式,我可以愉快地拥有一个无闪烁的richtextBox控件:

richTextBoxEx1.SuspendPainting();
richTextBoxEx1.AppendText("hey!");
richTextBoxEx1.ResumePainting();

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...