TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# PreviewKeyDown Event

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

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 Property and KeyDown


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf