How do you disable a DataGridView's keyboard shorcuts?
Asked Answered
D

3

6

I've just noticed that DataGridViews have a default shortcut so that whenever you press Ctrl + H, the DataGridView's editing control backspaces, and can delete your entire selection within the cell.

This can get quite annoying since I want to open a Replace box whenever Ctrl + H is pressed. Is there any way to stop the backspacing while still being able to use it to open the replace box?

I'm running C# 2.0, but I could update my application to 3.5 if the newer C# has a solution.

Disorientate answered 12/4, 2010 at 2:20 Comment(0)
E
5

This goes into your form code:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{     
  if (keyData == (Keys.Control | Keys.H))
  {
    //ShowReplaceDialog() or whatever it is you want to do here.
    return true; //we handled the key
  }

  return base.ProcessCmdKey(ref msg, keyData); //we didn't handle it
}
Emerick answered 12/4, 2010 at 4:34 Comment(3)
Thanks it works perfectly! Can you give me any pointers on when to override ProcessCmdKey instead of just handling a KeyDown event?Disorientate
Not sure, TBH. MSDN says: "This method is called during message preprocessing to handle command keys. Command keys are keys that always take precedence over regular input keys. Examples of command keys include accelerators and menu shortcuts."Emerick
How to keep Ctrl + c and Ctrl +v functionality intact with this. I am not able to use these shortcuts for copy/paste. Please assist.Resistencia
W
0

void m_dgv_KeyDown(object sender, KeyEventArgs e)
    {
               if (e.KeyCode == (Keys.Control | Keys.H))
                {
                  e.Handled = true;
                }
   }
Wholism answered 20/5, 2010 at 21:50 Comment(0)
C
0

/Before saving, place the focus on another control and then save.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{

    if (keyData == Keys.F5)
    {
        label1.Focus();
        btnSave_Click(null, null);
    }

    return base.ProcessCmdKey(ref msg, keyData); //we didn't handle it
}
Chappelka answered 17/1, 2024 at 1:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.