我有一个RichTextBox,我需要经常更新Text属性,但是当我这样做时,RichTextBox会因为在整个方法调用中刷新所有内容而"眨眼".
我希望找到一种简单的方法来暂时禁止屏幕刷新,直到我的方法完成,但我在网上找到的唯一一件事是覆盖WndProc方法.我采用了这种方法,但有一些困难和副作用,它也使调试更加困难.看起来似乎必须有更好的方法来做到这一点.有人能指出我更好的解决方案吗?
这是完整而有效的例子:
private const int WM_USER = 0x0400; private const int EM_SETEVENTMASK = (WM_USER + 69); private const int WM_SETREDRAW = 0x0b; private IntPtr OldEventMask; [DllImport("user32.dll", CharSet=CharSet.Auto)] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); public void BeginUpdate() { SendMessage(this.Handle, WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero); OldEventMask = (IntPtr)SendMessage(this.Handle, EM_SETEVENTMASK, IntPtr.Zero, IntPtr.Zero); } public void EndUpdate() { SendMessage(this.Handle, WM_SETREDRAW, (IntPtr)1, IntPtr.Zero); SendMessage(this.Handle, EM_SETEVENTMASK, IntPtr.Zero, OldEventMask); }
我问了原来的问题,最适合我的答案是BoltBait使用带有WM_SETREDRAW的SendMessage().它似乎比使用WndProc方法的副作用更少,并且在我的应用程序中的执行速度是LockWindowUpdate的两倍.
在我扩展的RichTextBox类中,我刚刚添加了这两个方法,每当我需要在进行一些处理时需要停止重新启动重新绘制时我都会调用它们.如果我想从RichTextBox类的外部执行此操作,我认为只需将"this"替换为对RichTextBox实例的引用即可.
private void StopRepaint() { // Stop redrawing: SendMessage(this.Handle, WM_SETREDRAW, 0, IntPtr.Zero); // Stop sending of events: eventMask = SendMessage(this.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero); } private void StartRepaint() { // turn on events SendMessage(this.Handle, EM_SETEVENTMASK, 0, eventMask); // turn on redrawing SendMessage(this.Handle, WM_SETREDRAW, 1, IntPtr.Zero); // this forces a repaint, which for some reason is necessary in some cases. this.Invalidate(); }