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

hal*_*rty 13 c# events scrollbar mousewheel winforms

当我使用带有滚动条的任何控件(ListBox,Panel,TextBox)时,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();
  }
 }
Run Code Online (Sandbox Code Playgroud)

Rod*_*pez 13

我遇到了同样的问题,对我来说有用的是为控件中的事件MouseEnter添加一个处理程序,一个是有或没有焦点的触发器.

private void chart1_MouseEnter(object sender, EventArgs e)
{
    chart1.Focus();
}
Run Code Online (Sandbox Code Playgroud)

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

  • 奇怪的是,在一台 W10 计算机上,相同的程序执行了鼠标滚轮操作,而在另一台计算机上却没有,直到我使用了您的解决方案。 (2认同)

hal*_*rty 2

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

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

我改为:

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

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


但问题是:

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

有任何想法吗 ?