C# Winform窗体中添加鼠标滚轮事件鼠标滚轮的方向判断
如图所示,在控件中没有直接的鼠标滚轮事件,需要我们进行手动添加。
下面以自定义控件MapComponent为例进行说明:
添加鼠标滚轮事件:
this.MouseWheel += new System.Windows.Forms.MouseEventHandler(LMap_MouseWheel);
其中LMap_MouseWheel为鼠标滚轮上下滚动事件的自定义函数,当鼠标滚轮上下移动时,该函数会响应鼠标滚轮事件。
//鼠标滚轮事件自定义函数(控件中没有直接的鼠标滚轮事件,需手动添加)
public void LMap_MouseWheel(object sender, MouseEventArgs e)
{
//当e.Delta > 0时鼠标滚轮是向上滚动,e.Delta < 0时鼠标滚轮向下滚动
if (e.Delta > 0)//滚轮向上
{
ZoomIn(); //放大
//MessageBox.Show("鼠标向上滑动");
}
else
{
ZoomOut();//缩小
//MessageBox.Show("鼠标向下滑动");
}
}
//沿中心缩放:变大
public void ZoomIn()
{
if (/*this.Status == LMapStatus.ZoomIn && */this.ZoomValue >= 0.02)
{
this.ZoomValue *= 0.5f;//缩放比例
this.ZoomValue_w *= 0.5f;//地图宽
this.ZoomValue_h *= 0.5f;//地图高
this.Display();
}
}
//沿中心缩放:缩小
public void ZoomOut()
{
if (/*this.Status == LMapStatus.ZoomOut && */this.ZoomValue <= 0.5)
{
this.ZoomValue *= 2.0f;
this.ZoomValue_w *= 2f;
this.ZoomValue_h *= 2f;
this.Display();
}
}