微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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();

原文地址:https://www.jb51.cc/csharp/100203.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐