C# PreviewKeyDown Event

PreviewKeyDown fixes a problem with keyboard input on DataGridView. It helps correct an issue with keyboard navigation. If the user focuses a cell and presses enter, the selection might not work properly.
Example. Let us closely examine the problem. The first thing I tried to do was use KeyCode and KeyDown. When the enter key was detected, my dialog would close and I would see the appropriate response.

However: When I went to open the dialog again, the selection would not be in the same place.

Tip: We can combine PreviewKeyDown and KeyDown. Take KeyDown, and set its event Handled property to true.

Example of KeyDown event handler: C# void dataGridView1_KeyDown(object sender, KeyEventArgs e) { // // Set the key down event has handled. We call our function // ProceedOpen in the PreviewKeyDown event instead. // if (e.KeyCode == Keys.Enter) { e.Handled = true; } }
We stop the KeyDown from moving the selection. However, before the runtime raises the KeyDown event, it will raise PreviewKeyDown. You can combine these events to eliminate the selection problem with it getting out of place.
Example of PreviewKeyDown event handler: C# void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { // // If the key pressed is enter, then call ProceedOpen. // if (e.KeyCode == Keys.Enter) { ProceedOpen(); } }
The code fixes selection problems. The selection stays in the same place, and ProceedOpen is called on the current cell. The user can open the dialog, move with the keyboard to a cell, press enter, and everything works as expected.
Summary. PreviewKeyDown can help your keyboard navigation techniques work well. This article helps provide you with a clue about this event and a possible use for it. PreviewKeyDown can solve selection moved problems in Windows Forms.KeyCode
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to