wpf KeyEventArgs.Key 到字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15359336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:02:10  来源:igfitidea点击:

KeyEventArgs.Key to char

c#wpftextboxkeyeventargs

提问by max_hassen

Is there any way to convert WPF's KeyEventArgs.Keyto Char?

有什么方法可以将 WPF 转换KeyEventArgs.KeyChar?

I tried to use KeyInterop:

我尝试使用KeyInterop

var x = (Char)KeyInterop.VirtualKeyFromKey(e.Key);

For numbers and letters it works fine, but for other characters it doesn't. E.g. for OemCommait returns '1/4' instead of ','.

对于数字和字母,它可以正常工作,但对于其他字符则不行。例如,OemComma它返回 '1/4' 而不是 ','。

I need it to prevent user of inputting into TextBoxany characters except numbers and separators (i.e. commas or periods).

我需要它来防止用户输入TextBox除数字和分隔符(即逗号或句点)以外的任何字符。

回答by kenny

UPDATE: the comment below found the original http://stackoverflow.com/a/5826175/187650

更新:下面的评论找到了原来的http://stackoverflow.com/a/5826175/187650

Found this somewhere that I've forgotten. Still using it, not sure what holes it has, but it's worked as far as I know.

在我忘记的地方找到了这个。仍在使用它,不确定它有什么漏洞,但据我所知,它确实有效。

public static class KeyEventUtility
{
    // ReSharper disable InconsistentNaming
    public enum MapType : uint
    {
        MAPVK_VK_TO_VSC = 0x0,
        MAPVK_VSC_TO_VK = 0x1,
        MAPVK_VK_TO_CHAR = 0x2,
        MAPVK_VSC_TO_VK_EX = 0x3,
    }
    // ReSharper restore InconsistentNaming

    [DllImport( "user32.dll" )]
    public static extern int ToUnicode(
        uint wVirtKey,
        uint wScanCode,
        byte[] lpKeyState,
        [Out, MarshalAs( UnmanagedType.LPWStr, SizeParamIndex = 4 )] 
        StringBuilder pwszBuff,
        int cchBuff,
        uint wFlags );

    [DllImport( "user32.dll" )]
    public static extern bool GetKeyboardState( byte[] lpKeyState );

    [DllImport( "user32.dll" )]
    public static extern uint MapVirtualKey( uint uCode, MapType uMapType );

    public static char GetCharFromKey( Key key )
    {
        char ch = ' ';

        int virtualKey = KeyInterop.VirtualKeyFromKey( key );
        var keyboardState = new byte[256];
        GetKeyboardState( keyboardState );

        uint scanCode = MapVirtualKey( (uint)virtualKey, MapType.MAPVK_VK_TO_VSC );
        var stringBuilder = new StringBuilder( 2 );

        int result = ToUnicode( (uint)virtualKey, scanCode, keyboardState, stringBuilder, stringBuilder.Capacity, 0 );
        switch ( result )
        {
        case -1:
            break;
        case 0:
            break;
        case 1:
            {
                ch = stringBuilder[0];
                break;
            }
        default:
            {
                ch = stringBuilder[0];
                break;
            }
        }
        return ch;
    }
}

回答by juFo

My first suggestion would be using PreviewTextInputand using the TextCompositionEventArgs. However this 'eats' the space-characters. For this 'space'-issue see:

我的第一个建议是使用PreviewTextInput和使用TextCompositionEventArgs。然而,这“吃掉”了空格字符。对于这个“空间”问题,请参见:

another solution would be using the KeyConverterin a KeyUpevent:

另一种解决方案是在KeyUp事件中使用KeyConverter

  KeyConverter kc = new KeyConverter();
  var str = kc.ConvertToString(e.Key);

For WPF: https://msdn.microsoft.com/en-us/library/system.windows.input.keyconverter(v=vs.110).aspxFor Winforms: https://msdn.microsoft.com/en-us/library/system.windows.forms.keysconverter.aspx

对于WPFhttps: //msdn.microsoft.com/en-us/library/system.windows.input.keyconverter( v = vs.110).aspx对于Winformshttps: //msdn.microsoft.com/en-我们/图书馆/system.windows.forms.keysconverter.aspx

Note that KeyConverter will give you the string "Space" instead of " ". (same for "Esc" when pressing the escape key.

请注意,KeyConverter 将为您提供字符串“Space”而不是“”。(按退出键时“Esc”相同。

Another WPF solution is using this in the KeyUpevent:

另一个 WPF 解决方案是在KeyUp事件中使用它:

((char)KeyInterop.VirtualKeyFromKey(e.Key))

回答by bash.d

Why such approach? There are different ways of preventing users from performing such input. For example, define an event-handler for the TextBox.TextChanged-event and when the input is not a decimal or a separator, revoke the input.

为什么采用这种方法?有多种方法可以防止用户执行此类输入。例如,为TextBox.TextChanged-event定义事件处理程序,当输入不是小数或分隔符时,撤销输入。

private void textChangedEventHandler(object sender, TextChangedEventArgs args){
//args contains a property `Changes` where you can see what happened
//check for invalid characters and revoke them
}

See TextChangedEventArgsand the event.

请参阅TextChangedEventArgs事件