使用任何带有滚动条的控件时,不会触发MouseWheel事件(在C#Windows窗体中)

时间:2010-01-19 15:03:09

标签: c# winforms events scrollbar mousewheel

MouseWheel事件不会触发 当我使用带滚动条的任何控件(ListBox,Panel,TextBox)时。

重现问题:

public class Form1 : Form
 {
  private readonly Button button1;
  private readonly TextBox textBox1;

  private void button1_MouseWheel(object sender, MouseEventArgs e)
  {
   ToString(); // doesn't fire when uncomment lines below
  }

  public Form1()
  {
   button1 = new Button();
   textBox1 = new TextBox();
   SuspendLayout();

   button1.Location = new System.Drawing.Point(80, 105);
   button1.Size = new System.Drawing.Size(75, 23);
   button1.MouseWheel += button1_MouseWheel;
   button1.Click += button1_Click;

   textBox1.Location = new System.Drawing.Point(338, 105);
   //textBox1.Multiline = true; // uncomment this
   //textBox1.ScrollBars = ScrollBars.Vertical;  // uncomment this 
   textBox1.Size = new System.Drawing.Size(100, 92);

   ClientSize = new System.Drawing.Size(604, 257);
   Controls.Add(textBox1);
   Controls.Add(button1);
   ResumeLayout(false);
   PerformLayout();
  }

  // Clicking the button sets Focus, but even I do it explicit Focus() or Select()
  // still doesn't work
  private void button1_Click(object sender, System.EventArgs e)
  {
   button1.Focus();
   button1.Select();
  }
 }

4 个答案:

答案 0 :(得分:13)

我遇到了同样的问题,对我来说有用的是为控件中的事件MouseEnter添加一个处理程序,无论是否有焦点都会触发该事件。

private void chart1_MouseEnter(object sender, EventArgs e)
{
    chart1.Focus();
}

之后我可以毫无问题地获得mouseWheel事件。

答案 1 :(得分:2)

您通常需要确保要处理MouseWheel事件的控件处于活动状态。

例如,尝试在Form Load(或Shown)事件中调用button1.Select(),然后使用滚轮。

例如:

private void Form1_Load(object sender, EventArgs e)
{
    button1.MouseWheel += new MouseEventHandler(button1_MouseWheel);

    button1.Select();  
}

答案 2 :(得分:2)

我找到了解决方案,gility是默认的“鼠标配置”。 联想USB光学鼠标默认配置为:

控制面板/鼠标/滚轮/ Whell-> 启用通用滚动;

我改为:

控制面板/鼠标/滚轮/ Whell-> 仅使用Microsoft Office 97滚动仿真

现在.net代码MouseWheel使用专注 控制


但问题是:

  • 如何在.net代码中修复它?
  • 如何在.net代码中检测到这种情况?

有什么想法吗?

答案 3 :(得分:0)

我尝试了你的例子,并且,无论这些行是否被注释,只有按钮被聚焦时,MouseWheel事件才会触发。此行为是设计使然。 (MouseWheel事件,如键盘事件,转到聚焦控件)