DataGridView 最右列用户增加大小不起作用

use*_*131 3 .net c# datagridview winforms

我在 WinForm 上的 DataGridView 上遇到了一个奇怪的问题。我可以通过鼠标调整所有列的大小,但对于最右边的我只能缩小而不能增加大小。

有谁知道如何解决这个问题?

Jim*_*imi 5

这是设计使然。当您单击/按住鼠标按钮时,鼠标将被捕获并且无法离开工作区,从而具有阻止调整大小的效果。你必须推动它。

我尝试不通过 P/Invoke 来释放捕获。
看看这是否适合您(当然,如果设置了任何 AutoSize 模式,则什么也不会发生)。

private bool IsLastColumn = false;
private bool IsMouseDown = false;
private int MouseLocationX = 0;
private int lastColumnIndex;

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
   var dgv = sender as DataGridView;
   lastColumnIndex = dgv.Columns
       .OfType<DataGridViewColumn>()
       .Where(c => c.Visible)
       .OrderBy(c => c.DisplayIndex)
       .Last()
       .Index;

   //Check if the mouse pointer is contained in last column boundaries
   //In the middle of it because clicking the divider of the row before
   //the last may be seen as inside the last too.
   Point location = new Point(e.X - (dgv.Columns[lastColumnIndex].Width / 2), e.Y);
   if (dgv.GetColumnDisplayRectangle(lastColumnIndex, true).Contains(location))
   {
      //Store a positive checks and the current mouse position
      IsLastColumn = true;
      IsMouseDown = true;
      MouseLocationX = e.Location.X;
   }
}

private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
   var dgv = sender as DataGridView;

   //If it's the last column and the left mouse button is pressed...
   if ((IsLastColumn) && (IsMouseDown) && (e.Button == MouseButtons.Left))
   {
      // Adding the width of the vertical scrollbar, if any.
      int cursorXPosition = e.X;
      if (dgv.Controls.OfType<VScrollBar>().Where(s => s.Visible).Count() > 0)
      {
          cursorXPosition += SystemInformation.VerticalScrollBarWidth;
      }

      //... calculate the offset of the movement.
      //You'll have to play with it a bit, though
      int colWidth = dgv.Columns[lastColumnIndex].Width;
      int colWidthOffset = colWidth + (e.X - MouseLocationX) > 0 ? (e.X - MouseLocationX) : 1;
      //If mouse pointer reaches the limit of the clientarea...
      if ((colWidthOffset > -1) && (cursorXPosition >= dgv.ClientSize.Width - 1))
      {
         //...resize the column and move the scrollbar offset
         dgv.HorizontalScrollingOffset = dgv.ClientSize.Width + colWidth + colWidthOffset;
         dgv.Columns[lastColumnIndex].Width = colWidth + colWidthOffset;
      }
   }
}

private void dataGridView1_MouseUp(object sender, MouseEventArgs e)
{
    IsMouseDown = false;
    IsLastColumn = false;
}
Run Code Online (Sandbox Code Playgroud)