Dmitry Polyanitsa
Dmitry Polyanitsa

Reputation: 1093

Handling mouse wheel and keyboard events while a mouse button is pressed

I have a custom WinForms control (derived from Control) in which I override OnMouseXXX and OnKeyXXX events.

I want to handle wheel and/or keyboard events while the mouse button is pressed (i.e. OnMouseDown was fired, but OnMouseUp wasn't fired yet). For some reason, I cannot get any of these until I release the mouse button.

Please advise on this matter. Using interop/unsafe code (if needed) would be OK, using a timer to read the keyboard state is not.

Upvotes: 0

Views: 1231

Answers (1)

Idle_Mind
Idle_Mind

Reputation: 39152

Instead of a global hook, you can go one level up and use IMessageFilter() instead. This will work for when your application is focused only. Not sure what level you need to work at...

public partial class MyUserControl : UserControl
{

    private MyFilter filter;

    public MyUserControl()
    {
        InitializeComponent();
        filter = new MyFilter();
        filter.LButtonScroll += new MyFilter.LBUTTONSCROLLDELEGATE(filter_LButtonScroll);
        Application.AddMessageFilter(filter);
    }

    private void filter_LButtonScroll()
    {
        Console.WriteLine("WM_MOUSEWHEEL while LBUTTONDOWN");
    }

    private class MyFilter : IMessageFilter
    {
        private bool LBUTTONDOWN = false;
        private const int WM_LBUTTONDOWN = 0x201;
        private const int WM_LBUTTONUP = 0x202;
        private const int WM_MOUSEWHEEL = 0x20a;

        public delegate void LBUTTONSCROLLDELEGATE();
        public event LBUTTONSCROLLDELEGATE LButtonScroll;

        public bool PreFilterMessage(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_LBUTTONDOWN:
                    LBUTTONDOWN = true;
                    break;

                case WM_MOUSEWHEEL:
                    if (LBUTTONDOWN)
                    {
                        if (LButtonScroll != null)
                        {
                            LButtonScroll();
                        }
                    }
                    break;

                case WM_LBUTTONUP:
                    LBUTTONDOWN = false;
                    break;
            }
            return false;
        }

    }
}

Upvotes: 1

Related Questions