msmolcic
msmolcic

Reputation: 6577

Scrolling windows form on mousewheel

I have windows form with vertical scrollbar and user can scroll up and down normally while control that does not handle WM_MOUSEWHEEL is selected because form itself process that event, therefore scrolling works perfectly fine.

However, when I select multiline textbox for example I can't scroll my form on mousewheel because WM_MOUSEWHEEL is handled by multiline textbox. I found this solution on StackOverflow and it works just fine:

public bool PreFilterMessage(ref Message m)
{
    if (m.Msg == 0x020a)
    {
        NativeMethods.SendMessage(this.Handle, m.Msg, m.WParam, m.LParam);
        return true;
    }
    return false;
}

internal class NativeMethods
{
    [DllImport("user32.dll")]
    public static extern IntPtr SendMessage(IntPtr hWnd, Int32 Msg, IntPtr wParam, IntPtr lParam);
}

The form scrolls up and down on mousewheel event no matter which child control is focused, but my boss does not want to use this solution because he fears it could somehow crash on another PC with different Windows or something. Anyhow, I would be satisfied if I could remove focus from children controls when user clicks on form, so I tried this:

private void MyWindowsForm_MouseDown(object sender, MouseEventArgs e)
{
    this.Focus();
}

It does not work since focus is automatically set to the first child control on the form.

My question is: "Is there any way to remove focus from child controls when user clicks on the form so I can scroll my form using mousewheel normally?"

Hopefully you can understand what I'm trying to do. Thanks in advance!

Upvotes: 2

Views: 2555

Answers (1)

Lukasz M
Lukasz M

Reputation: 5723

According to suggestion posted here How to remove the focus from a TextBox in WinForms?, You can use a little trick to achieve this effect. Just set focus to a Label control in Your form. The Label control looks the same whether it's focused or not, so it appears as focus is not set anywhere. The control must be visible, however, if You don't have any labels on Your form, You can just add one with empty Text value. This will make the Form appear as if no focus is set.

Edit

As You mentioned in the comment, focusing on a specific control causes the Form to be automatically scrolled to bring that control into view, which is not desired in this case. However, You can use a Panel control (let's say its Name is myPanel) with Dock property set to Fill (so that it covers the whole form), set AutoScroll to true and put all the controls in it. Then, in order to remove focus from any control, You can write myPanel.Focus() to set focus on the Panel itself. I've quickly tested this and it seems to work as expected.

Upvotes: 1

Related Questions