Shift + mouse wheel horizontal scrolling
In your designer file, you'll need to manually add a MouseWheel event delegate.
this.richTextBox.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.RichTextBox_MouseWheel);
Then, in your code behind, you can add the following.
private const int WM_SCROLL = 276; // Horizontal scroll
private const int SB_LINELEFT = 0; // Scrolls one cell left
private const int SB_LINERIGHT = 1; // Scrolls one line right
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
private void RichTextBox_MouseWheel(object sender, MouseEventArgs e)
{
if (ModifierKeys == Keys.Shift)
{
var direction = e.Delta > 0 ? SB_LINELEFT : SB_LINERIGHT;
SendMessage(this.richTextBox.Handle, WM_SCROLL, (IntPtr)direction, IntPtr.Zero);
}
}
For more information on the const values, see the following SO: How do I programmatically scroll a winforms datagridview control?
UPDATE
Use Alvin's solution if possible. It's way better.
If you are creating your own control derived from UserControl
or ScrollControl
or Form
, you can use this simple solution:
protected override void OnMouseWheel(MouseEventArgs e)
{
if (this.VScroll && (Control.ModifierKeys & Keys.Shift) == Keys.Shift)
{
this.VScroll = false;
base.OnMouseWheel(e);
this.VScroll = true;
}
else
{
base.OnMouseWheel(e);
}
}
Explanation
If a control has AutoScroll
and is displaying scrollbars, when you scroll the mouse wheel you will get the following behaviour:
- If no scrollbars are enabled, it does nothing.
- If only vertical scrollbar is enabled, it scrolls vertical scrollbar.
- If only horizontal scrollbar is enabled, it scrolls horizontal scrollbar.
- If both vertical and horizontal scrollbars are enabled, it scrolls vertical scrollbar.
Noticing this behaviour, I figured out this hack to override OnMouseWheel
of the control, then if the vertical scrollbar is enabled and Shift is held down, it disables the vertical scrollbar before calling base.OnMouseWheel
. This will trick the control in scrolling the horizontal scrollbar (behaviour 3 as shown above).