system.windows.input.keyEventArgs 키를 숯으로 변환합니다
-
21-08-2019 - |
문제
이벤트 args를 a로 가져와야합니다 char
, 그러나 키 열거를 캐스팅하려고 할 때 나는 통과 된 것과 완전히 다른 글자와 상징을 얻습니다.
키를 숯으로 어떻게 올바르게 변환합니까?
이것이 제가 시도한 것입니다
ObserveKeyStroke(this, new ObervableKeyStrokeEvent((char)((KeyEventArgs)e.StagingItem.Input).Key));
편집 : Args에 키 코드 속성도 없습니다. inputmanager.current.prenotifyinput 이벤트에서 가져오고 있습니다.
해결책
보다 캐릭터를 동등한 시스템으로 변환하는 방법 .windows.input.key enum 값?사용 KeyInterop.VirtualKeyFromKey
대신에.
다른 팁
익숙해지기에는 약간 필요하지만 키 값 자체를 사용할 수 있습니다. 입력을 알파 너머리로 제한하고 약간의 여분의 추가로 제한하려는 경우 아래 코드가 도움이 될 수 있습니다.
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;
}
}
그것은 나를 위해 일한다 :
마지막 항목을 기반으로 WPF에는 그러한 이벤트가 없다는 것을 알았습니다. PreNotifyInput
, 그러나 나는 찾았고 동등한 것을 발견했다 PreviewTextInput
먼저 나는 a RegExp
,하지만 나는 그것을 작동시킬 수 없다면 간단한 것을 사용합니다. 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;
}
나는 이것이 오래되었음을 알고 있지만, 답은 실제로 질문에 대답하지 않는 것 같습니다. 다른 문자가 돌아 오는 이유는 당신이 그것을 그냥 캐스팅하려고 할 때 char
당신은 열거적인 값을 'char'로 캐스팅하고 있습니다. 하지만:
var keyPressed = e.key.ToString();
잘 작동합니다. 눌린 키를 문자열로 반환합니다. 그런 다음 길이를 확인합니다. == 1이면 숯, 번호 또는 기호입니다. 1보다 크면 특별한 키입니다.
문자 만 원한다면 할 수 있습니다. keyPressed[0];
이것이 내가하는 방법입니다.
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)
}
}
Prenotifyinput 핸들러 내부에서 다음과 같은 것을 시도하십시오.
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];
}
}
다른 라우팅 된 이벤트에 대해 여러 번 올리므로 특정 이벤트를 필터링 할 수 있습니다.