Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a System.Windows.Input.KeyEventArgs key to a char

I need to get the event args as a char, but when I try casting the Key enum I get completely different letters and symbols than what was passed in.

How do you properly convert the Key to a char?

This is what I've tried

ObserveKeyStroke(this, new ObervableKeyStrokeEvent((char)((KeyEventArgs)e.StagingItem.Input).Key));

Edit: I also don't have the KeyCode property on the args. I'm getting them from the InputManager.Current.PreNotifyInput event.

like image 997
Brandon Avatar asked May 12 '09 21:05

Brandon


Video Answer


2 Answers

See How to convert a character in to equivalent System.Windows.Input.Key Enum value? Use KeyInterop.VirtualKeyFromKey instead.

like image 85
Wallstreet Programmer Avatar answered Oct 21 '22 10:10

Wallstreet Programmer


It takes a little getting used to, but you can just use the key values themselves. If you're trying to limit input to alphanumerics and maybe a little extra, the code below may help.

    private bool bLeftShiftKey = false;
    private bool bRightShiftKey = false;

    private bool IsValidDescriptionKey(Key key)
    {
        //KEYS ALLOWED REGARDLESS OF SHIFT KEY

        //various editing keys
        if (
        key == Key.Back ||
        key == Key.Tab ||
        key == Key.Up ||
        key == Key.Down ||
        key == Key.Left ||
        key == Key.Right ||
        key == Key.Delete ||
        key == Key.Space ||
        key == Key.Home ||
        key == Key.End
        ) {
            return true;
        }

        //letters
        if (key >= Key.A && key <= Key.Z)
        {
            return true;
        }

        //numbers from keypad
        if (key >= Key.NumPad0 && key <= Key.NumPad9)
        {
            return true;
        }

        //hyphen
        if (key == Key.OemMinus)
        {
            return true;
        }

        //KEYS ALLOWED CONDITITIONALLY DEPENDING ON SHIFT KEY

        if (!bLeftShiftKey && !bRightShiftKey)
        {
            //numbers from keyboard
            if (key >= Key.D0 && key <= Key.D9)
            {
                return true;
            }
        }

        return false;
    }

    private void cboDescription_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.LeftShift)
        {
            bLeftShiftKey = true;
        }

        if (e.Key == Key.RightShift)
        {
            bRightShiftKey = true;
        }

        if (!IsValidDescriptionKey(e.Key))
        {
            e.Handled = true;
        }
    }

    private void cboDescription_PreviewKeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.LeftShift)
        {
            bLeftShiftKey = false;
        }

        if (e.Key == Key.RightShift)
        {
            bRightShiftKey = false;
        }
    }
like image 45
fortune Avatar answered Oct 21 '22 11:10

fortune