How can I scroll my panel using my mousewheel?

2019-02-21 07:00发布

I have a panel on my form with AutoScroll set to true so a scrollbar appears automatically.

How can I make it so a user can use his mouse wheel to scroll the panel? Thanks SO.

9条回答
Summer. ? 凉城
2楼-- · 2019-02-21 07:25

Moving the scroll wheel should trigger the control's MouseMove event. The MouseEventArgs argument has a property named Delta, which gives the (signed) number of notches that the mouse wheel has moved. You can use this property to scroll the panel.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-02-21 07:30

I am using a windows form with BorderStyle set to none, where I use a panel to have all my controls in, so it looks nice (color difference and such..) was having the same issue while I had other forms that worked fine.

What did I forgot:

   public myForm()
   {
        InitializeComponent();
        this.DoubleBuffered = true;
   }

DoubleBuffered is magical I noticed..

查看更多
对你真心纯属浪费
4楼-- · 2019-02-21 07:36

Make sure that your panel has focus. And this is simple code to scroll your panel scrollbar. Hope this help. :) enter code here

        if(e.Delta > 0)
        {

            if (pnlContain.VerticalScroll.Value - 2 >= pnlContain.VerticalScroll.Minimum)
                pnlContain.VerticalScroll.Value -= 2;
            else
                pnlContain.VerticalScroll.Value = pnlContain.VerticalScroll.Minimum;
        }
        else
        {
            if (pnlContain.VerticalScroll.Value + 2 <= pnlContain.VerticalScroll.Minimum)
                pnlContain.VerticalScroll.Value += 2;
            else
                pnlContain.VerticalScroll.Value = pnlContain.VerticalScroll.Maximum;
        }
查看更多
乱世女痞
5楼-- · 2019-02-21 07:37

The panel or a control in the panel must have focus. Note that if the control with focus has scroll bars, it will scroll instead of the panel.

查看更多
乱世女痞
6楼-- · 2019-02-21 07:38

What worked for me was adding panel1_MouseEnter EventHandler:

private void panel1_MouseEnter(object sender, EventArgs e)
{
    panel1.Focus();
}
查看更多
太酷不给撩
7楼-- · 2019-02-21 07:38

In the designer file, you can add the following line of code. the MouseWheel event is not doumented in Events list in the Properties window.

this.Panel1.MouseWheel+= System.Windows.Forms.MouseEventHandler(this.Panel1_MouseWheel);

Panel1_MouseWheel will be triggered when you roll the mouse weel

Add the code in the .cs file

查看更多
登录 后发表回答