我有一个奇怪的问题。在Winforms应用程序中,我有一个DataGridView,在其中我实现了一些用箭头键移动的代码,然后输入键...
class CalibDataGridView : System.Windows.Forms.DataGridView
{
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
int row = 0;
int col = 0;
// return base.ProcessCmdKey(ref msg, keyData);
switch (keyData)
{
case Keys.Down:
return true;
case Keys.Up:
return true;
case Keys.Right:
row = this.CurrentCell.RowIndex;
col = this.CurrentCell.ColumnIndex;
while (true)
{
col++;
if (col == this.Columns.Count)
{
row++;
col = 0;
}
if (row == this.Rows.Count)
{
col = 0;
row = 0;
}
if (!this[col, row].ReadOnly && this[col, row].Visible) break;
}
this.CurrentCell = this[col, row];
return true;
case Keys.Left:
row = this.CurrentCell.RowIndex;
col = this.CurrentCell.ColumnIndex;
while (true)
{
col--;
if (col < 0)
{
row--;
col = this.Columns.Count - 1;
}
if (row < 0)
{
row = this.Rows.Count - 1;
col = this.Columns.Count - 1;
}
if (!this[col, row].ReadOnly && this[col, row].Visible) break;
}
this.CurrentCell = this[col, row];
return true;
case Keys.Enter:
row = this.CurrentCell.RowIndex;
col = this.CurrentCell.ColumnIndex;
while (true)
{
row++;
if (row == this.Rows.Count)
{
row = 0;
}
if (!this[col, row].ReadOnly && this[col, row].Visible) break;
}
this.CurrentCell = this[col, row];
return true;
default:
return base.ProcessCmdKey(ref msg, keyData);
}
}
}
该代码正常运行,但是当按下选项卡键时,我有一个问题实现功能,以移至下一个控件。我在dataGridView的PreviewKeydown功能中添加了一些代码:
private void dgvRepeatability1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.PageDown && tbcMain.SelectedIndex > 0)
{
tbcMain.SelectedIndex--; //changes tab page
}
else if (e.KeyCode == Keys.PageUp && tbcMain.SelectedIndex < 7)
{
tbcMain.SelectedIndex++;
}
else if (e.KeyCode == Keys.Tab) //does not work like it should!!!!
{
Console.Beep(1000, 200);
this.SelectNextControl((Control)sender, true, true, true, true);
}
}
最后一个代码以奇怪的方式工作...当将其触发在背景中的某个地方时,请像应该更改重点(它哔哔声,下一个控制更改背景颜色,以便我可以看到它是集中的(,但是我失去了专注于整个表单...我可以按Tab或Arrow键或任何其他键,什么也不会发生。
如果我最小化表单,然后再次将其最大化,则焦点将像首先一样到达下一个控件,并且一切都可以正常工作。
我还尝试以.select((和.focus((为例,并且不起作用。
事先感谢您的帮助!
您可以使用selectnextcontrol:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if ( e.KeyCode == Keys.Tab )
{
e.Handled = true;
this.SelectNextControl((Control)sender, true, true, true, true);
}
您也可以自己找到下一个控件:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if ( e.KeyCode == Keys.Tab )
{
e.Handled = true;
var dataGrid = (DataGridView) sender;
var tabIndex = dataGrid.TabIndex;
var controls = this.Controls.Cast<Control>().Where( r => r.TabIndex > tabIndex );
if ( controls.Any() )
{
controls.OrderBy(r => r.TabIndex).First().Select();
}
else
{
this.Controls.Cast<Control>()
.Where( r => r.TabIndex <= tabIndex )
.OrderBy( r => tabIndex )
.First()
.Select();
}
}
}