简体   繁体   中英

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

The mousewheel event needs to be set up.

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

this.MouseWheel+= new MouseEventHandler(Form1_MouseWheel);

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.

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);
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM