user2558874
user2558874

Reputation: 57

How can I get the scrollbar position on panel? WinForms C#

I'm trying to get the scrollbar position on a panel, but it olny works if I scroll it by clicking and dragging the scroolbar or clicking its scrolling buttons.

If I scroll the panel using the mouse wheel it doesn't work.

Here's my code:

if (mypanel.HorizontalScroll.Value > 500)
        {
            lbl1.Text = "A";
        }
        if (mypanel.HorizontalScroll.Value < 300)
        {
            lbl1.Text = "B";
        }

Upvotes: 3

Views: 22006

Answers (1)

King King
King King

Reputation: 63317

The Scroll and MouseWheel are different. When you scroll, that means you have to use the ScrollBar to scroll it, the message WM_HSCROLL and WM_VSCROLL will be sent to the control. When you use Mouse you can also scroll with a condition that there is 1 child control focused in the scrollable container like Panel, the message WM_MOUSEWHEEL will be sent to the control. So to achieve what you want, you have to register handlers for both the events Scroll and MouseWheel like this:

private void HandleScroll(){
    if (mypanel.HorizontalScroll.Value > 500) {
        lbl1.Text = "A";
    }
    else if (mypanel.HorizontalScroll.Value < 300) {
        lbl1.Text = "B";
    }
}
//place this code in your form constructor after InitializeComponent()
panel1.Scroll += (s,e) => {
   HandleScroll();
};
panel1.MouseWheel += (s,e) => {  
   HandleScroll();
};

Upvotes: 5

Related Questions