In this article I’ll show you how to disable RichTextBox‘s Smooth Scrolling – aka make RichTextBox scroll line by line. I know this is a problem for many developers, it was a problem for me too, so that’s why I decided to post this code snippet.
Fixing it
Well, there’s no easy way to fix it and since there’s no other option, you’ll have to make a custom RichTextBox and override the WndProc() function.
Basically, you have to disable the original smooth scrolling and then use SendMessage() send scroll messages.
Before starting, you’ll need to add this namespace:
|
1 2 |
using System.Runtime.InteropServices; |
We’ll use the following line to send a message to the RichTextBox to scroll
|
1 2 3 4 5 6 |
SendMessage(this.Handle, WM_VSCROLL, (IntPtr)wParam, IntPtr.Zero); //wParam (3rd parameter) can be 0 or 1 // 0 to scroll up // 1 to scroll down |
Now, you must create your own control, which inherits from RichTextBox. I’ll post the complete code, and I’ll explain it by using comments:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
class editedRichTextBox : RichTextBox { [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam); //this message is sent to the control when we scroll using the mouse private const int WM_MOUSEWHEEL = 0x20A; //and this one issues the control to perform scrolling private const int WM_VSCROLL = 0x115; protected override void WndProc(ref Message m) //here we override WndProc { if (m.Msg == WM_MOUSEWHEEL) //we check if the mousewheel is used (we need to scroll) { if ((int)m.WParam > 0) //if the wParam is greater than 0 we scroll up { //each line sends the message to scroll one line up | it scrolls 3 lines SendMessage(this.Handle, WM_VSCROLL, (IntPtr)0, IntPtr.Zero); SendMessage(this.Handle, WM_VSCROLL, (IntPtr)0, IntPtr.Zero); SendMessage(this.Handle, WM_VSCROLL, (IntPtr)0, IntPtr.Zero); } else // else we scroll down { //here send the commands to scroll down 3 lines SendMessage(this.Handle, WM_VSCROLL, (IntPtr)1, IntPtr.Zero); SendMessage(this.Handle, WM_VSCROLL, (IntPtr)1, IntPtr.Zero); SendMessage(this.Handle, WM_VSCROLL, (IntPtr)1, IntPtr.Zero); } } else base.WndProc(ref m); //if the message isn't WM_MOUSEWHEEL we ignore it } } |
