代码之家  ›  专栏  ›  技术社区  ›  Sheikh Rahat Ali

鼠标滚轮事件火灾

  •  0
  • Sheikh Rahat Ali  · 技术社区  · 16 年前

    在MouseWheel事件中调用我的私有方法时遇到问题。事实上,当我只增加一个变量或在标题栏中显示某个内容时,鼠标滚轮事件会被正确触发,但是当我想调用一个私有方法时,该方法只被调用一次,这不是我想根据滚动速度调用该方法的要求,即当滚动完成一次时,缓慢调用私有方法一次,但当滚动以高速完成时,根据滚动速度多次调用私有方法。

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

    如何根据鼠标滚轮滚动的速度多次调用私有方法?

    1 回复  |  直到 16 年前
        1
  •  2
  •   Radoslav Hristov    16 年前

    你可以试着用 MouseEventArgs.Delta 用于计算呼叫数的字段:

            int timesToCall = Math.Abs(e.Delta/120);
    
            for (int k = 0; k < timesToCall; ++k)
            {
                this.LaunchThisEvent();
            }
    

    `

    推荐文章