Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

How can I make the ListView scroll even when it doesn't have focus?

like image 849
Brian Gillespie Avatar asked Sep 17 '08 20:09

Brian Gillespie


1 Answers

"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
}
like image 63
Chris W Avatar answered Sep 24 '22 03:09

Chris W