简体   繁体   English

C# ListView 鼠标滚轮无焦点滚动

[英]C# ListView mouse wheel scroll without focus

I'm making a WinForms app with a ListView set to detail so that several columns can be displayed.我正在制作一个将 ListView 设置为 detail 的 WinForms 应用程序,以便可以显示多个列。

I'd like for this list to scroll when the mouse is over the control and the user uses the mouse scroll wheel.当鼠标悬停在控件上并且用户使用鼠标滚轮时,我希望此列表滚动。 Right now, scrolling only happens when the ListView has focus.现在,滚动仅在 ListView 具有焦点时发生。

How can I make the ListView scroll even when it doesn't have focus?即使没有焦点,如何使 ListView 滚动?

"Simple" and working solution: “简单”和有效的解决方案:

public class FormContainingListView : Form, IMessageFilter
{
    public FormContainingListView()
    {
        // ...
        Application.AddMessageFilter(this);
    }

    #region mouse wheel without focus

    // 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);

    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() & 0xffff, m.LParam.ToInt32() >> 16);
            IntPtr hWnd = WindowFromPoint(pos);
            if (hWnd != IntPtr.Zero && hWnd != m.HWnd && System.Windows.Forms.Control.FromHandle(hWnd) != null)
            {
                SendMessage(hWnd, m.Msg, m.WParam, m.LParam);
                return true;
            }
        }
        return false;
    }

    #endregion
}

You'll normally only get mouse/keyboard events to a window or control when it has focus.您通常只会在具有焦点时将鼠标/键盘事件发送到窗口或控件。 If you want to see them without focus then you're going to have to put in place a lower-level hook.如果您想在没有焦点的情况下看到它们,那么您将不得不放置一个较低级别的挂钩。

Here is an example low level mouse hook 这是一个低级鼠标钩子的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM