Pregunta

Necesito conseguir los argumentos de eventos como una char, pero cuando trato de fundición de la enumeración clave consigo completamente diferentes letras y símbolos de lo que se ha pasado.

¿Cómo convertir correctamente la clave para un char?

Esto es lo que he tratado

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

Edit: Asimismo, no tienen la propiedad KeyCode en los argumentos. Yo les estoy haciendo desde el evento InputManager.Current.PreNotifyInput.

¿Fue útil?

Otros consejos

Se necesita un poco de tiempo para acostumbrarse, pero sólo puede usar los mismos valores clave. Si usted está tratando de limitar la entrada de caracteres alfanuméricos y tal vez un poco más, el código de abajo puede ayudar.

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

Ese trabajo para mí:

basa en la última entrada i encontró que en WPF no hay tal evento PreNotifyInput, pero he encontrado y equivalente PreviewTextInput

En primer trato con un RegExp, pero no puedo hacer que funcione, entonces yo uso un simple indexOf.

private bool ValidChar(string _char)
{
   string Lista = @" ! "" # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z ";
   return Lista.IndexOf(_char.ToUpper()) != -1;
   //System.Text.RegularExpressions.Regex RegVal = new System.Text.RegularExpressions.Regex(@"(?<LETRAS>[A-Z]+)+(?<NUMERO>[0-9]+)+(?<CAR>[!|""|#|$|%|&|'|(|)|*|+|,|\-|.|/|:|;|<|=|>|?|@]+)+");
   //return RegVal.IsMatch(_char);
}

private void textBoxDescripcion_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    if (!ValidChar(e.Text))
         e.Handled = true;
}

Sé que esto es viejo, pero ninguna de las respuestas parecen responder a la pregunta en realidad. La razón de un char diferente va a volver es porque cuando se acaba de tratar de echarlo a un char necesita modelar el valor de enumeración a un char '. Sin embargo:

var keyPressed = e.key.ToString();

Funciona muy bien. Devuelve la tecla pulsada como una cadena. A continuación, se comprueba la longitud. Si se trata de == 1 entonces es un char, número o símbolo. Si es mayor que 1 es una llave especial.

Si lo que desea es el carbón a continuación, puede hacer keyPressed[0];

Esto es cómo lo hago.

private void scrollViewer_KeyDown(object sender, KeyEventArgs e)
{
    if (!e.IsRepeat)
    {
        var keyPressed = e.Key.ToString();
        if(keyPressed.Length == 1)
            CharKeyPressed(keyPressed[0]);
        else if(keyPressed.Length > 1)
            HandleSpecialKey(keyPressed)
    }
}

Dentro de su manejador PreNotifyInput, intentar algo como esto:

        if (e.StagingItem.Input is System.Windows.Input.TextCompositionEventArgs)
        {
            if (!String.IsNullOrEmpty((e.StagingItem.Input as System.Windows.Input.TextCompositionEventArgs).Text))
            {
                Char c = (e.StagingItem.Input as System.Windows.Input.TextCompositionEventArgs).Text[0];
            }
        }

Se plantea varias veces para los diferentes eventos enrutados, por lo que puede filtrar por una en particular.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top