本文转载于 cnblogs 风雨彩虹.
在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方法
/// <summary>
/// 滚动方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void FormSample_MouseWheel(object sender, MouseEventArgs e)
{
//获取光标位置
Point mousePoint = new Point(e.X, e.Y);
//换算成相对本窗体的位置
mousePoint.Offset(this.Location.X, this.Location.Y);
//判断是否在panel内
if (panel_content.RectangleToScreen(panel_content.DisplayRectangle).Contains(mousePoint))
{
//滚动
panel_content.AutoScrollPosition = new Point(0, panel_content.VerticalScroll.Value - e.Delta);
}
}