Converter uma chave System.Windows.Input.KeyEventArgs para um char
-
21-08-2019 - |
Pergunta
Eu preciso para obter os args evento como um char
, mas quando eu tento lançar o enum Chave fico completamente diferentes letras e símbolos do que o que foi passado.
Como você converter corretamente a chave para um char?
Este é o que eu tentei
ObserveKeyStroke(this, new ObervableKeyStrokeEvent((char)((KeyEventArgs)e.StagingItem.Input).Key));
Edit: Eu também não têm a propriedade KeyCode sobre os argumentos. Eu estou recebendo-os a partir do evento InputManager.Current.PreNotifyInput.
Solução
como converter um personagem no valor System.Windows.Input.Key Enum equivalente?
Use KeyInterop.VirtualKeyFromKey
vez.
Outras dicas
É preciso um pouco para se acostumar, mas você pode apenas usar os valores de chave próprios. Se você está tentando entrada limite para alfanuméricos e talvez um pouco mais, o código abaixo ajuda Maio.
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;
}
}
Esse trabalho para mim:
Com base na última entrada eu achei que no WPF não existe tal PreNotifyInput
evento, mas eu achei e PreviewTextInput
equivalente
Primeiro eu tento com um RegExp
, mas eu não posso fazê-lo funcionar, então eu uso um indexOf
simples.
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;
}
Eu sei que este é antiga, mas nenhuma das respostas parecem realmente responder à pergunta. A razão um char diferente está voltando é porque quando você apenas tentar lançá-lo a um char
você está lançando o valor enum para um 'char'. No entanto:
var keyPressed = e.key.ToString();
Funciona muito bem. Retorna a tecla pressionada como uma string. Então você verificar o comprimento. Se é == 1, então é um char, número ou símbolo. Se for maior que 1 é uma chave especial.
Se você quiser apenas o caractere que você pode então fazer keyPressed[0];
Isto é como eu fazê-lo.
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 do seu manipulador PreNotifyInput, tentar algo como isto:
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];
}
}
Ela levanta várias vezes para os diferentes eventos roteados, assim você pode querer filtro para um particular.