DataGridView keydown 事件在 C# 中不起作用 [英] DataGridView keydown event not working in C#

查看:51
本文介绍了DataGridView keydown 事件在 C# 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DataGridView keydown 事件在我编辑单元格内的文本时不起作用.

DataGridView keydown event is not working when I am editing text inside a cell.

我正在指定快捷键 Alt+S 来保存数据,它在单元格未处于编辑模式时有效,但如果它处于编辑模式,则下面的代码无效

I am assigning shortcut Alt+S to save the data, it works when cell is not in edit mode, but if it is in edit mode below code is not working

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
 {
    if (e.KeyData == (Keys.Alt | Keys.S))
    {
         //save data
    }
 }

推荐答案

每当单元格处于编辑模式时,其托管控件都会接收 KeyDown 事件而不是父 包含它的 DataGridView. 这就是为什么只要单元格不在编辑模式下(即使它被选中),您的键盘快捷键就会起作用,因为您的 DataGridView 控件本身接收KeyDown 事件.但是,当您处于编辑模式时,单元格包含的编辑控件正在接收事件,并且没有任何反应,因为它没有附加您的自定义处理程序例程.

Whenever a cell is in edit mode, its hosted control is receiving the KeyDown event instead of the parent DataGridView that contains it. That's why your keyboard shortcut is working whenever a cell is not in edit mode (even if it is selected), because your DataGridView control itself receives the KeyDown event. However, when you are in edit mode, the edit control contained by the cell is receiving the event, and nothing happens because it doesn't have your custom handler routine attached to it.

我花了太多时间调整标准 DataGridView 控件以按照我希望的方式处理编辑提交,我发现解决这种现象的最简单方法是通过子类化现有的 DataGridView 控件并覆盖其 ProcessCmdKey 函数.每当在 DataGridView 顶部按下一个键时,无论它是否处于编辑模式,您在此处输入的任何自定义代码都会运行.

I have spent way too much time tweaking the standard DataGridView control to handle edit commits the way I want it to, and I found that the easiest way to get around this phenomenon is by subclassing the existing DataGridView control and overriding its ProcessCmdKey function. Whatever custom code that you put in here will run whenever a key is pressed on top of the DataGridView, regardless of whether or not it is in edit mode.

例如,您可以执行以下操作:

For example, you could do something like this:

class MyDataGridView : System.Windows.Forms.DataGridView
{
    protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
    {

        MessageBox.Show("Key Press Detected");

        if ((keyData == (Keys.Alt | Keys.S)))
        {
            //Save data
        }

        return base.ProcessCmdKey(ref msg, keyData);
    }
}

另请参阅相关文章(虽然有些旧):如何使用 Visual C# 捕获控件中的击键

Also see related, though somewhat older, article: How to trap keystrokes in controls by using Visual C#

这篇关于DataGridView keydown 事件在 C# 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆