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

前端之家收集整理的这篇文章主要介绍了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();

猜你在找的C#相关文章