Windows窗体:捕获MouseWheel

n0t*_*ter 6 .net mousewheel winforms

我有一个Windows窗体(在C#.NET中工作).

表单顶部有几个面板,底部有一些ComboBoxes和DataGridViews.

我想在顶部面板上使用滚动事件,但是如果选择一个例如ComboBox,焦点就会丢失.面板包含各种其他控件.

当鼠标悬停在任何面板上时,我怎么能总是收到鼠标滚轮事件?到目前为止,我尝试使用MouseEnter/MouseEnter事件,但没有运气.

Jon*_*ant 13

您所描述的内容听起来像是要复制Microsoft Outlook的功能,在这种情况下,您无需实际单击以聚焦控件以在其上使用鼠标滚轮.

这是一个需要解决的相对高级的问题:它涉及实现IMessageFilter包含表单的接口,查找WM_MOUSEWHEEL事件并将它们引导到鼠标悬停在其上的控件.

这是一个例子(从这里):

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsApplication1 {
  public partial class Form1 : Form, IMessageFilter {
    public Form1() {
      InitializeComponent();
      Application.AddMessageFilter(this);
    }

    public bool PreFilterMessage(ref Message m) {
      if (m.Msg == 0x20a) {
        // WM_MOUSEWHEEL, find the control at screen position m.LParam
        Point pos = new Point(m.LParam.ToInt32());
        IntPtr hWnd = WindowFromPoint(pos);
        if (hWnd != IntPtr.Zero && hWnd != m.HWnd && Control.FromHandle(hWnd) != null) {
          SendMessage(hWnd, m.Msg, m.WParam, m.LParam);
          return true;
        }
      }
      return false;
    }

    // P/Invoke declarations
    [DllImport("user32.dll")]
    private static extern IntPtr WindowFromPoint(Point pt);
    [DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
  }
}
Run Code Online (Sandbox Code Playgroud)

请注意,此代码对应用程序中的所有表单都有效,而不仅仅是主表单.