Monday, June 29, 2020

KeyCode vs. KeyData vs. KeyValue

When trying to examine user keystrokes in Windows Forms, the .Net Framework and .Net Core offer a variety of properties:

 

Keys: an enumeration in the System.Windows.Forms namespace that Specifies key codes and modifiers.

 

KeyCode: returns the System.Windows.Forms.Keys value that is the key code for the event.

 

KeyData: Returns the System.Windows.Forms.Keys representing the key code for the key that was pressed, combined with modifier flags that indicate which combination of CTRL, SHIFT, and ALT keys was pressed at the same time.

 

KeyValue: returns the integer representation of the KeyCode property.

 

 

Example:

tbUnitPrice.PreviewKeyDown += new PreviewKeyDownEventHandler(this.tbUnitPrice_PreviewKeyDown);  //Add event handler to capture keystroke

 

 

        private void tbUnitPrice_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)

        {

            var keycode = e.KeyCode;

            var keydata = e.KeyData;

            var keyValue = e.KeyValue;

 

            if ( (keycode == Keys.Tab) || (keycode == Keys.Enter) )

            {

                dgParts.CurrentCell = dgParts.Rows[dgParts.CurrentRow.Index + 1].Cells[0];                   //Move to the 1st cell of the next row

 

            }

        }

 

2 comments:

  1. How to get these data from wm_keydown message ? I mean, without the help of winforms or .net.

    ReplyDelete
    Replies
    1. That depends, what platform/language are you using?

      Delete