MouseWheel事件不会触发,因为TextBox会窃取Focus

时间:2012-09-25 08:48:35

标签: c#

我正在尝试以下代码:

public Form1()
{
    InitializeComponent();
    this.MouseWheel += new MouseEventHandler(Form1_MouseWheel);
}

private void Form1_MouseWheel(object sender, MouseEventArgs e)
{
    textBox1.Text += "delta : " + e.Delta + "\r\n";
}

但事件似乎永远不会发生。然后我注意到文本框在表单显示后立即获得焦点,事实上,在我删除它之后,事件开始工作。

现在,问题:

  1. 如果表单是顶部窗口,我怎样才能触发事件, 即使我有textarea吗?
  2. 我应该简单地将相同的事件添加到textarea还是有一个     更简单的方法,我无法看到?
  3. 有没有办法等待"滚轮滚动"在结束之前结束         火灾的事件?我需要以指数方式增加整数值         根据车轮滚动的时间长短

2 个答案:

答案 0 :(得分:0)

将Form1_MouseWheel添加到表单和文本框(或者可能只是文本框) 在此代码中,彼此之后一秒钟内的所有鼠标滚轮运动都属于同一系列。

public partial class Form1 : Form
{
    private Timer second = new Timer();
    private int wheelMoves = 0;

    public Form1()
    {
        second.Interval = 1000;
        second.Tick += new EventHandler(second_Tick);
        InitializeComponent();
    }

    void second_Tick(object sender, EventArgs e)
    {
        second.Stop();
        // DoStuff with wheelmoves.
        textBox1.Text = wheelMoves.ToString() + " " + (wheelMoves * wheelMoves).ToString();
        wheelMoves = 0;
    }

    void Form1_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        // reset the timer.
        second.Stop();
        second.Start();
        // Count the number of times the wheel moved.
        wheelMoves++;
    }
}

编辑:如果您添加另一个控件并使其获得焦点,则无需将事件处理程序添加到文本框中。这使文本框滚动功能保持不变,并且还调用自定义MouseWheel事件。

答案 1 :(得分:0)

这里最可能的是文本框自动窃取焦点,因为操作系统可能会自动假设任何鼠标滚轮都指向它(因为它是唯一可用的文本编辑控件)。

可能的解决方案:

  1. 您可以按照文本框中的说法添加鼠标滚轮事件
  2. 您可以在自定义文本框类中使用SetStyle强制创建永远无法获得焦点的文本框,如下所示:
  3. class unfocusableTextBox : TextBox
        {
            public unfocusableTextBox(){
                   SetStyle(ControlStyles.Selectable, false);
            }
        }
    
相关问题