How to get pressed char from KeyEventArgs Winforms

How to get pressed char from KeyEventArgs Winforms

Added by Mind Hunter updated on Thursday, May 10, 2018

How to get pressed char from KeyEventArgs Winforms:

Here is a small snippet which will get the pressed char at keydown event. Sometimes we need to get Char at key down event rather than keypress event.

In this example we are making a custom TextBox control and we need Char at its KeyDown Event.

public class cTextBox : TextBox
{
	[DllImport("user32.dll")]
    public static extern int ToUnicode(uint virtualKeyCode, uint scanCode,byte[] keyboardState,
		[Out, MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)]
    	StringBuilder receivingBuffer,
        int bufferSize, uint flags);        

	protected override void OnKeyDown(KeyEventArgs e)
    {            
    	char r = CharFromKeys(e.KeyCode, e.Shift, e.Control);
        //Logic to handel this char
		//
		//
        base.OnKeyDown(e);
	}
    public char CharFromKeys(Keys keys, bool shift, bool altGr)
    {
    	char r = '\0';
        var buf = new StringBuilder(256);
        var keyboardState = new byte[256];
        if (shift)
        	keyboardState[(int)Keys.ShiftKey] = 0xff;
        if (altGr)
        {
        	keyboardState[(int)Keys.ControlKey] = 0xff;
            keyboardState[(int)Keys.Menu] = 0xff;
        }
        if (ToUnicode((uint)keys, 0, keyboardState, buf, 256, 0) > 0)
        	r = buf[0];
        return r;
    }
}

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected