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

查看:110
本文介绍了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 控件进行子类化,并覆盖其 中的Windows。rel =nofollow> 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.

例如,你可以这样做:

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);
    }
}

另请参阅相关文章, a href =http://support.microsoft.com/kb/320584 =nofollow>如何使用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天全站免登陆