14

当我使用带有滚动条的任何控件(列表框、面板、文本框)时,MouseWheel 事件不会触发。

重现问题:

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

4 回答 4

15

我遇到了同样的问题,对我有用的是在控件中为事件 MouseEnter 添加一个处理程序,该处理程序在有或没有焦点的情况下触发。

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

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

于 2012-02-13T19:36:20.450 回答
2

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

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

我改为:

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

现在在 .net 代码中 MouseWheel 与Focused Control一起使用。


但问题是:

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

有任何想法吗 ?

于 2010-01-20T08:26:53.177 回答
2

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

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

例如:

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

    button1.Select();  
}
于 2010-01-19T15:09:27.247 回答
0

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

于 2010-01-19T15:16:41.210 回答