MouseWheel Event Fire

筅森魡賤 提交于 2019-12-11 18:21:32

问题


I have a problem on calling my private method on MouseWheel event. In fact my mouse wheel event gets fired properly when i only increment a variable or display something in Title bar etc. But when i want to call a private method, that method gets called only one time which is not the requirement i want to call that method depending on the speed of scroll i.e. when scroll is done one time slowly call the private method one time but when the scroll is done in high speed call the private method more than one time depending on the scroll speed.

For further explanation i am placing the sample code which displays the value of i in Title bar and add it in the Listbox control properly depending on the scroll speed but when i want to call the private method more than one time depending upon the scroll speed, that method gets called only one time.

public partial class Form1 : Form
{
    ListBox listBox1 = new ListBox();
    int i = 0;

    public Form1()
    {
        InitializeComponent();

        // Settnig ListBox control properties
        this.listBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                    | System.Windows.Forms.AnchorStyles.Left)
                    | System.Windows.Forms.AnchorStyles.Right)));
        this.listBox1.FormattingEnabled = true;
        this.listBox1.Location = new System.Drawing.Point(13, 13);
        this.listBox1.Name = "listBox1";
        this.listBox1.Size = new System.Drawing.Size(259, 264);
        this.listBox1.TabIndex = 0;

        // Attaching Mouse Wheel Event
        this.listBox1.MouseWheel += new MouseEventHandler(Form1_MouseWheel);

        // Adding Control
        this.Controls.Add(this.listBox1);
    }

    void Form1_MouseWheel(object sender, MouseEventArgs e)
    {
        i++;
        this.Text = i.ToString();
        this.listBox1.Items.Add(i.ToString());            

        // Uncomment the following line to call the private method
        // this method gets called only one time irrelevant of the
        // mouse wheel scroll speed.
        // this.LaunchThisEvent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.listBox1.Select();
    }

    private void LaunchThisEvent()
    {
        // Display message each time 
        // this method gets called.
        MessageBox.Show(i.ToString());
    }
}

How to call the private method more than one time depending upon the speed of the mouse wheel scroll?


回答1:


You can try using the MouseEventArgs.Delta field to calculate the number of calls:

        int timesToCall = Math.Abs(e.Delta/120);

        for (int k = 0; k < timesToCall; ++k)
        {
            this.LaunchThisEvent();
        }

`



来源:https://stackoverflow.com/questions/2825380/mousewheel-event-fire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!