Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't fire MouseWheel event in C# Windows Forms

First off, the mousewheel event is not listed in Visual Studio 2008's events pane which is very annoying.

I found the correct format online though, and wrote this into my code:

    private void Form1_MouseWheel(object sender, MouseEventArgs e)
    {
        Debug.WriteLine("Foo");
    }

...from which I'm getting no response when the mousewheel is rotated.

I'm doing this in my code's main class area, and the designer contains only the one form/window/whatever so the mouse isn't losing focus.

namespace BlahBlah
{
    public partial class Form1 : Form
    {

And by contrast, I have this method right above the mousewheel one and it works fine:

    private void Form1_MouseClick(object sender, MouseEventArgs e)
    {
        Debug.WriteLine("Foo");
    }

If I had to guess, I'm thinking I'm not correctly linking the code to the form (aka: all the stuff that visual studio would do for me if I added this event through the designer's events panel). But I could be wrong or just be making some silly error.

Can you help me get ANY kind of response when the mouse wheel is rotated? Thanks!

like image 887
ck_ Avatar asked Jul 27 '09 19:07

ck_


4 Answers

The mousewheel event needs to be set up.

Add this to Form1's constructor (After InitalizeComponents();)

this.MouseWheel+= new MouseEventHandler(Form1_MouseWheel);
like image 101
Kurisu Avatar answered Sep 23 '22 06:09

Kurisu


I don't have enough reputation to respond with a comment, but the answer to your side question is that the delegates do need to be setup. However when you create one by double clicking it in the properties pane the code is automatically generated and placed in the *.designer.cs file in the InitializeComponent method.

like image 43
marco0009 Avatar answered Sep 23 '22 06:09

marco0009


It's best in this case to override the OnMouseWheel member function rather than register to the event. For example:

public class MyFrm : Form
{
    protected override void OnMouseWheel(MouseEventArgs e)
    {
        /*Handle the mouse wheel here*/
        base.OnMouseWheel(e);
    }
}
like image 2
lmat - Reinstate Monica Avatar answered Sep 23 '22 06:09

lmat - Reinstate Monica


I don't know how to subscribe to that particular event but you can override the appropriate method on the form, instead.

like image 1
Mark Simpson Avatar answered Sep 20 '22 06:09

Mark Simpson