【发布时间】:2013-10-21 21:41:57
【问题描述】:
我正在创建一个逻辑来在我的表单中没有焦点(outlook 样式)的鼠标位置下滚动控件。我可以使用 IMessageFilter 实现这种行为。但是,如果按下“SHIFT”键,我将面临应用水平滚动的困难。
using System;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing;
public partial class UI : Form
{
MouseWheelMessageFilter mouseFilter = null;
public UI()
{
InitializeComponent();
mouseFilter = new MouseWheelMessageFilter();
Application.AddMessageFilter(mouseFilter);
this.FormClosed += (o, e) => Application.RemoveMessageFilter(mouseFilter);
}
}
public class MouseWheelMessageFilter : IMessageFilter
{
[DllImport("user32.dll")]
public static extern IntPtr WindowFromPoint(Point pt);
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
public const int MK_CONTROL = 0x0008;
public const int MK_SHIFT = 0x0004;
public const int WM_MOUSEWHEEL = 0x020A;
public const int WM_MOUSEHWHEEL = 0x020E;
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_MOUSEWHEEL)
{
var shiftKeyDown = (char)((Keys)m.WParam) == MK_SHIFT;
//apply the scroll to the control at mouse location
Point pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16);
IntPtr hWnd = WindowFromPoint(pos);
if (hWnd != IntPtr.Zero && hWnd != m.HWnd && Control.FromHandle(hWnd) != null)
{
if (shiftKeyDown)
//TODO: Horizontal scroll - Not working WM_MOUSEHWHEEL (0x020E)
//SendMessage(hWnd, WM_MOUSEHWHEEL, m.WParam, m.LParam);
else
//Vertical Scroll - working
SendMessage(hWnd, WM_MOUSEWHEEL, m.WParam, m.LParam);
return true;
}
}
return false;
}
}
我需要在 //TODO 部分做什么才能使水平滚动正常工作?
【问题讨论】:
-
很多应用程序不支持 WM_MOUSEHWHEEL。在我从事的一个项目中,我们必须编写代码来查找滚动条并以编程方式操作它们(这有很多问题)。
-
再补充一点:向不属于您的窗口发送消息时最好使用
PostMessage而不是SendMessage。如果您必须发送消息(而不是发布),请使用SendMessageTimeout。
标签: c# winapi imessagefilter