Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
        }
like image 539
user2558874 Avatar asked Dec 03 '25 14:12

user2558874


1 Answers

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();
};
like image 66
King King Avatar answered Dec 06 '25 06:12

King King