Jiew Meng
Jiew Meng

Reputation: 88257

MouseScroll event does not trigger when TextBox is scrollable

I found that when I attach a MouseWheel event to my UserControl or a TextBox, it does not trigger if the TextBox is scrollable. It will scroll the textbox and not trigger MouseWheel, can I make it such that it runs MouseWheel and then after doing something e.Cancel it so that the TextBox does not scroll?

UPDATE: With Video & Code

Video

http://screenr.com/ZGF

Code

http://www.mediafire.com/?x3o09dz6dr5zoym

public MainWindow()
{
    InitializeComponent();
    textBox.MouseWheel += (s, e) =>
    {
        Random rand = new Random();
        Debug.WriteLine(rand.NextDouble());
    };
}

Upvotes: 1

Views: 2426

Answers (1)

Hans Passant
Hans Passant

Reputation: 941942

I assume you mean that the MouseWheel event on the UserControl won't trigger. That's normal, the TextBox is happy to accept the message when it is multiline. The reason that the MouseWheel event is not visible in the designer. The parent window will only see the message when the control with the focus won't process it.

Not sure if you should fix this, the user would really expect the text box to scroll. But you can by intercepting the message so the text box can't see it and passing the message to the parent. Add a new class to your project, paste the code shown below. Compile. Drop the new control from the top of the toolbox.

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class MyTextBox : TextBox {
    protected override void WndProc(ref Message m) {
        if (m.Msg == 0x20a && this.Parent != null) {
            PostMessage(this.Parent.Handle, m.Msg, m.WParam, m.LParam);
        }
        else base.WndProc(ref m);
    }
    [DllImport("user32.dll")]
    private static extern IntPtr PostMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
}

Upvotes: 3

Related Questions