题
我正在制作一个 WinForms 应用程序,其中 ListView 设置为详细信息,以便可以显示多个列。
我希望当鼠标悬停在控件上并且用户使用鼠标滚轮时滚动此列表。目前,仅当 ListView 具有焦点时才会发生滚动。
即使没有焦点,如何使 ListView 滚动?
解决方案
通常,只有当窗口或控件具有焦点时,您才会将鼠标/键盘事件发送到该窗口或控件。如果你想在没有焦点的情况下看到它们,那么你将不得不放置一个较低级别的钩子。
其他提示
“简单”且可行的解决方案:
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
}
不隶属于 StackOverflow