如何在不按Tab键的情况下强制DataGridView当前单元格轮廓

是否有某种方法可以使DataGridView的当前单元格在按Tab键时始终具有围绕它的虚线边框? 我注意到,如果你曾经按过Tab键一次,那么当前的单元格总是有边框,但是我想从头开始有那个边框,而不必按Tab键。

目前我以编程方式发送Tab键,如下所示:

 SendKeys.Send("{TAB}"); 

但这很糟糕,如果可以的话,我宁愿有一个合适的解决方案。

编辑:我忘了提到SelectionMode设置为FullRowSelect ,我不打算改变它。 我希望边框轮廓只围绕当前单元格以及整个行被突出显示。

创建一个新类以inheritanceDataGridView并覆盖ShowFocusCues属性 – 返回True始终显示焦点矩形,或返回False永远不显示它。 如果你想随心所欲地改变它,你甚至可以添加一个公共属性来公开它。

 public class DataGridViewFocused : DataGridView { public bool ShowFocus { get; set; } protected override bool ShowFocusCues { get { return this.ShowFocus; } } } DataGridViewFocused dataGridView1 = new DataGridViewFocused(); dataGridView1.ShowFocus = true; 

注意:这只会关注CurrentCell因为它就是它的行为方式。 因此,即使设置了FullRowSelect ,也只会聚焦突出显示的行中的一个选定单元格。

这种行为似乎是在Windows窗体中硬编码。 我认为你无法找到更好的编码方式。

我可以建议你的一个建议是处理DataGridView.CellPainting事件并手动绘制边框。 然后,您将能够使用所需的样式绘制边框,以便当前单元格对于用户而言比使用“TAB”方法更加明显。 以下是带有红色虚线边框的示例:

 private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (dataGridView1.CurrentCell != null && e.RowIndex != -1 && e.ColumnIndex != -1 && dataGridView1.CurrentCell.RowIndex == e.RowIndex && dataGridView1.CurrentCell.ColumnIndex == e.ColumnIndex) { e.Paint(e.ClipBounds, e.PaintParts); var pen = new Pen(Color.Red) { DashStyle = DashStyle.Dash }; var rect = new Rectangle(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Width - 2, e.CellBounds.Height - 2); e.Graphics.DrawRectangle(pen, rect); e.Handled = true; } }