【发布时间】:2015-06-03 01:25:23
【问题描述】:
我有一个带有 KeyDown 和 KeyUp 处理程序的 DataGridView。在某些情况下,我想禁用 Enter 键的默认行为(取消选择文本并专注于下一行),就像这样:
private void View_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && Condition)
{
// Special flow - do logic and CANCEL default event effect
SpecialFlow = true;
...
e.Handled = true; // That doesn't do the job
}
}
private void View_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && Condition && SpecialFlow)
{
// Special flow - do logic and continue normally
SpecialFlow = false;
...
}
}
我发现了一些似乎不符合我需求的解决方案:
- 使用挂钩拦截应用程序中的所有键盘事件 - 我需要更多检查才能做到这一点。
- 删除所有事件处理程序 - 但一旦密钥启动,我需要它们。
- 实施新的控制 - 过度杀伤。
简单地说,有没有办法在处理程序之后(在默认处理之前)并且仅在特殊流程中拦截关键事件?
已解决:
我遇到的问题是根本没有调用KeyDown,因为单元格处于编辑模式,基本上没有办法阻止Enter结束编辑模式的默认行为。所以我添加了一个标志,用于在编辑模式结束后在编辑模式下返回所选文本 - 在 KeyUp 处理程序中。
差不多是这样的:
private void View_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (Condition)
EndEditFlag = true;
}
private void View_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && Condition)
{
if (EndEditFlag)
{
EndEditFlag = false;
// Select by previously saved selection data - revert CellEndEdit
View.CurrentCell = View.Rows[...].Cells[...];
SelectText(...);
}
// Special flow - do logic
}
}
【问题讨论】:
标签: c# .net datagridview event-handling