📜  允许使用滚轮鼠标滚动datagridview c#(1)

📅  最后修改于: 2023-12-03 15:36:44.311000             🧑  作者: Mango

允许使用滚轮鼠标滚动DataGridView C#

在使用DataGridView时,我们希望能够使用滚轮鼠标进行垂直和水平滚动。本文将介绍如何实现这一功能。

步骤
  1. 设置DataGridViewMouseWheel事件

    private void dataGridView1_MouseWheel(object sender, MouseEventArgs e)
    {
        if (e.Delta > 0)
            dataGridView1.FirstDisplayedScrollingRowIndex--;
        else if (e.Delta < 0)
            dataGridView1.FirstDisplayedScrollingRowIndex++;
    }
    

    得益于 Windows Forms 控件的事件机制,我们可以将 MouseWheel 事件与 DataGridView 相关联。

  2. 禁用默认事件

    禁用默认的滚轮事件是为了防止在滚动DataGridView时窗体自动滚动。我们需要使用以下代码禁用默认事件:

    protected override void OnMouseWheel(MouseEventArgs e)
    {
        HandledMouseEventArgs args = e as HandledMouseEventArgs;
        args.Handled = true;
    }
    

    在自定义控件中,在 OnMouseWheel 方法中调用 HandledMouseEventArgs.Handled 属性以禁用默认的滚轮事件。

示例代码
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // 将 DataGridView 的 MouseWheel 事件与自定义的事件处理程序相关联
            dataGridView1.MouseWheel += new MouseEventHandler(dataGridView1_MouseWheel);
        }

        // 自定义事件处理程序,当鼠标滚轮滚动时,滚动 DataGridView
        private void dataGridView1_MouseWheel(object sender, MouseEventArgs e)
        {
            if (e.Delta > 0)
                dataGridView1.FirstDisplayedScrollingRowIndex--;
            else if (e.Delta < 0)
                dataGridView1.FirstDisplayedScrollingRowIndex++;
        }

        // 禁用默认的滚轮事件
        protected override void OnMouseWheel(MouseEventArgs e)
        {
            HandledMouseEventArgs args = e as HandledMouseEventArgs;
            args.Handled = true;
        }
    }
}
总结

通过上述步骤,我们可以轻松地实现在DataGridView中使用滚轮鼠标滚动的功能。除此之外,我们还可以根据需要在滚轮事件中添加水平滚动的代码。