views:

2012

answers:

3

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.

+3  A: 

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

Wallstreet Programmer
A: 

Try something like the following:

//Assuming e is of type KeyEventArgs
char pressedChar = ((Char)e.KeyCode);
Andreas Grech
Sorry, as I said, I don't have the KeyCode property on this event.
Brandon
ah sorry, didn't see your edit.
Andreas Grech
A: 

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;
        }
    }
fortune