winform dataGridView 滚动条跟随鼠标操作移动

   private void Form1_Load(object sender, EventArgs e)
    {
        dataGridView1.MouseWheel += new System.Windows.Forms.MouseEventHandler(dataGridView1_MouseWheel);
        dataGridView1.Scroll += DataGridView1_Scroll;
        dataGridView1.MouseMove += DataGridView1_MouseMove;
    }
    private int HorizontalOffset;
    private int VerticalScrollIndex;
    private void DataGridView1_Scroll(object sender, ScrollEventArgs e)
    {
        try
        {
            if (e.ScrollOrientation == ScrollOrientation.VerticalScroll)
            {
                VerticalScrollIndex = e.NewValue;
            }
            else if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
            {
                HorizontalOffset = e.NewValue;
            }

        }
        catch { }
    }
    private int indexss = 10;
    private int interX = 0;
    private void DataGridView1_MouseMove(object sender, MouseEventArgs e)
    {
        Point point = PointToClient(MousePosition);
        if (interX == 0)
        {
            interX = point.X;
            return;
        }
        if (point.X > interX)
        {
            if (dataGridView1.Width <= dataGridView1.HorizontalScrollingOffset) dataGridView1.HorizontalScrollingOffset = dataGridView1.Width;
            else dataGridView1.HorizontalScrollingOffset += indexss;
        }
        else
        {
            if (dataGridView1.HorizontalScrollingOffset - indexss < 0) dataGridView1.HorizontalScrollingOffset = 0;
            else dataGridView1.HorizontalScrollingOffset -= indexss;
        }
        interX = point.X;
    }
    private void dataGridView1_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        dataGridView1.Focus();
        //SendKeys.Send(e.Delta.ToString());

        // SendKeys.Send("^{End}");             //这句代码是设置滚动条直接到最底
        //        其中的{ End}
        //        这个是不是很熟悉,没错就是键盘上的到未尾的键
        //        可以相应的换成{ Home}
        //        记录第一行,{ PgUp}
        //        上一记录,{ PgDn}
        //        下一记录
    }

你可能感兴趣的:(winform dataGridView 滚动条跟随鼠标操作移动)