How to handle KeyEvents in a DataGridViewCell?

DataGridViewCell doesn’t have any events, but you can listen for the KeyDown event on the DataGridView itself and then look at which cell is selected:

public void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.F1)
    {
        var selectedCell = dataGridView.SelectedCells[0];
        // do something with selectedCell...
    }
}

I found this code in a forum, and it works.

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
   DataGridViewTextBoxEditingControl tb = (DataGridViewTextBoxEditingControl)e.Control;
   tb.KeyPress += new KeyPressEventHandler(dataGridViewTextBox_KeyPress);    
   e.Control.KeyPress += new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
}
    
private void dataGridViewTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
   //when i press enter,bellow code never run?
   if (e.KeyChar==(char)Keys.Enter)
   {
      MessageBox.Show("You press Enter");
   }
}