使用鼠标滚轮的水平滚动(C#& WinAPI)

时间:2013-10-14 10:33:41

标签: c# winapi imessagefilter

我正在创建一个逻辑来在我的表单中滚动鼠标位置下没有焦点(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部分我需要做什么才能使水平滚动工作?

1 个答案:

答案 0 :(得分:2)

这只是猜测,我不能自己测试,但我注意到你只是在过滤:

if (m.Msg == WM_MOUSEWHEEL)

您是否需要单独过滤WM_MOUSEHWHEEL:

if (m.Msg == WM_MOUSEHWHEEL)

那么也许您不必测试换档键?

编辑:这就是我的想法:

public bool PreFilterMessage(ref Message m)
{
    if (m.Msg == WM_MOUSEWHEEL || m.Msg == WM_MOUSEHWHEEL)
    {
        //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)
        {
            SendMessage(hWnd, m.Msg, m.WParam, m.LParam);
            return true;
        }
    }
    return false;
}

很抱歉,如果这不起作用,我现在无法编译它来测试它,只是猜测如果用户按住SHIFT键不会得到WM_MOUSEWHEEL(改为获取WM_MOUSEHWHEEL)