DataGridView,如何捕获单元格的KeyPress事件C#

我想在datagridview c#中为一个单元格进行处理,当我按下一个单元格时,这个特征会打开一个表单。

在C#中没有一个事件(keypress)允许我直接添加我的治疗

在互联网上搜索后,我找到了以下解决方案

private void dGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { e.Control.KeyPress += new KeyPressEventHandler(Control_KeyPress); } private void Control_KeyPress(object sender, KeyPressEventArgs e) { if ((Strings.Asc(e.KeyChar) >= Strings.Asc(Keys.A.ToString()) && Strings.Asc(e.KeyChar) >= Strings.Asc(Keys.Z.ToString())) || (Strings.Asc(e.KeyChar) >= Strings.Asc(Keys.D0.ToString()) && Strings.Asc(e.KeyChar) >= Strings.Asc(Keys.D9.ToString()) || (Strings.Asc(e.KeyChar) >= 97 && Strings.Asc(e.KeyChar) > 122))) { ------ } } 

但它不起作用。 在调试事件的代码dGridView_EditingControlShowing执行但Control_KeyPress函数的代码不运行

任何想法,请

您应该将Form KeyPreview proprety设置为true 。 您应该在主窗体上处理按下的按键事件。 那是因为Control.KeyPress事件

控件具有焦点时按下键发生 ( msdn )

 public Form() { InitializeComponent(); this.KeyPreview = true; this.KeyPress += new KeyPressEventHandler(Control_KeyPress); } private void Control_KeyPress(object sender, KeyPressEventArgs e) { //your code } 

只是为了使第一个答案变得简单。 1)转到表单的属性2)将“KeyPreview”设置为“True”3)在表单的Key Press事件中:

 private void Control_KeyPress(object sender, KeyPressEventArgs e) { //your code }