在winform开发中,通过设置Panel的AutoScroll属性来控制滚动条是否显示,但显示滚动条的时候,鼠标的滚轮是无法控制Panel里面的滚动条的,只能控制Form的滚动条,当我们需要控制Panel的滚动条的时候,应该怎么做呢?
1、拖一个Panel到Form里面,修改Name为panel_content,并设置AutoScroll为True
2、在Form的Load事件中添加下面的代码
this.MouseWheel += FormSample_MouseWheel;
3、在Form类中添加FormSample_MouseWheel方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary>
2 /// 滚动方法
3 /// </summary>
4 /// <param name="sender"></param>
5 /// <param name="e"></param>
6 void FormSample_MouseWheel(object sender, MouseEventArgs e)
7 {
8 //获取光标位置
9 Point mousePoint = new Point(e.X, e.Y);
10 //换算成相对本窗体的位置
11 mousePoint.Offset(this.Location.X, this.Location.Y);
12 //判断是否在panel内
13 if (panel_content.RectangleToScreen(panel_content.DisplayRectangle).Contains(mousePoint))
14 {
15 //滚动
16 panel_content.AutoScrollPosition = new Point(0, panel_content.VerticalScroll.Value - e.Delta);
17 }
18 }
2 /// 滚动方法
3 /// </summary>
4 /// <param name="sender"></param>
5 /// <param name="e"></param>
6 void FormSample_MouseWheel(object sender, MouseEventArgs e)
7 {
8 //获取光标位置
9 Point mousePoint = new Point(e.X, e.Y);
10 //换算成相对本窗体的位置
11 mousePoint.Offset(this.Location.X, this.Location.Y);
12 //判断是否在panel内
13 if (panel_content.RectangleToScreen(panel_content.DisplayRectangle).Contains(mousePoint))
14 {
15 //滚动
16 panel_content.AutoScrollPosition = new Point(0, panel_content.VerticalScroll.Value - e.Delta);
17 }
18 }
通过以上步骤即可用鼠标滚轮控制Panel里面的滚动条了。
作者:风雨彩虹
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。