C# PreviewKeyDown

Lightning bolt

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.

This C# article shows how to use PreviewKeyDown in Windows Forms. It helps keyboard navigation work correctly.

Examples

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 he went to open the dialog again, the selection would not be in the same place. 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;
    }
}

Stops selection. That means we stop the KeyDown from moving the selection. However, before the runtime raises the KeyDown event, it will raise the PreviewKeyDown event. Basically, 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();
    }
}
Question and answer

Does it really work? Yes—the code shown does fix selection problems. With this technique, 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

The C# programming language

We looked at the PreviewKeyDown event handler in the Windows Forms platform using the C# programming language. PreviewKeyDown can help your keyboard navigation techniques work well. This article was written to provide you with a clue about the PreviewKeyDown event and a possible use for it. PreviewKeyDown can solve selection moved problems in Windows Forms.

KeyCode Property and KeyDown Windows Forms
.NET