【问题标题】:C# ListView mouse wheel scroll without focusC# ListView 鼠标滚轮滚动无焦点
【发布时间】:2008-09-17 20:13:56
【问题描述】:

我正在制作一个 WinForms 应用,其中 ListView 设置为 detail,以便可以显示多个列。

当鼠标悬停在控件上并且用户使用鼠标滚轮时,我希望此列表滚动。目前,只有在 ListView 具有焦点时才会发生滚动。

如何让 ListView 在没有焦点的情况下滚动?

【问题讨论】:

    标签: c# .net listview scroll


    【解决方案1】:

    “简单”且可行的解决方案:

    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
    }
    

    【讨论】:

    • 这会失去其他控件的焦点。
    【解决方案2】:

    您通常只会在窗口或控件获得焦点时将鼠标/键盘事件传递给它。如果您想在没有焦点的情况下看到它们,那么您将不得不放置一个较低级别的钩子。

    Here is an example low level mouse hook

    【讨论】:

    • 这个答案可以改进,比如摘录示例代码的相关区域并演示如何修改它以适应 OP 的 actual 问题——目前该示例显示了如何单击按钮时打印光标位置,而不是如何在悬停时启用滚轮。
    猜你喜欢
    • 2013-04-09
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 2011-09-29
    • 2018-08-22
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多