为DataGridView增加鼠标滚轮功能

本文解决了在DataGridView中,只有当鼠标移到滚动栏时滚动才生效的问题。通过引入API函数WindowFromPoint,判断鼠标位置,实现在GridView内任意位置使用滚轮滚动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Q:DataGridView 在鼠标移到滚动栏时,滚动才有效,怎样当我的光标在其中滚动就有效呢?

1:首先引用API函数WindowFromPoint(该函数获得包含指定点的窗口的句柄),判断当前鼠标指针是否在GridView中

 [DllImport("user32.dll", EntryPoint = "WindowFromPoint")]
 static extern IntPtr WindowFromPoint(Point pt);

 2:为GridView增加鼠标滚动事件
 private void orderGrid_MouseEnter(object sender, EventArgs e)
  {
       this.MouseWheel += orderGrid_MouseWheel;
  }


  public void orderGrid_MouseWheel(object sender, MouseEventArgs e)
   {     
         Point p = PointToScreen(e.Location);
         if ((WindowFromPoint(p)) == orderGrid.Handle)//鼠标指针在框内
         {
                if (e.Delta > 0)
                {
                    if (orderGrid.FirstDisplayedScrollingRowIndex - 5 < 0)
                    {
                        orderGrid.FirstDisplayedScrollingRowIndex = 0;
                    }
                    else
                    {
                        orderGrid.FirstDisplayedScrollingRowIndex = orderGrid.FirstDisplayedScrollingRowIndex - 5;
                    }
                }
                else
                {
                    orderGrid.FirstDisplayedScrollingRowIndex = orderGrid.FirstDisplayedScrollingRowIndex + 5;
                }
            }
     }




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值