【问题标题】:How to get the localized keyboard-key-name in VS C#如何在 VS C# 中获取本地化的键盘键名
【发布时间】:2016-05-09 16:27:05
【问题描述】:

我有一个ToolStripMenuItem,它具有ShortcutKeys Ctrl+Oemcomma(即Ctrl+,)。我想在项目名称附近显示该快捷方式,以便用户可以看到该快捷方式。不幸的是,它显示为Ctrl+Oemcomma,而不是更容易理解的Ctrl+,

有一个属性 ShortcutKeyDisplayString 覆盖了自动创建的字符串,这样就可以修复它。但是,一旦应用程序以不调用控制键Ctrl 的语言运行(例如在德国称为Strg),ShortcutKeyDisplayString 看起来就错了,因为所有其他自动创建的快捷方式描述都被翻译(即,如果在英文操作系统中,描述显示为Ctrl+S,在德语操作系统中则显示为Strg+S)。

是否有一个函数可以返回一个键的本地化名称,以便我可以使用它来设置 ShortcutKeyDisplayString? IE。我正在寻找一个函数,它在英语操作系统中返回 Ctrl,在德语操作系统中返回 Strg 等。我尝试了 System.Windows.Forms.Keys.Control.ToString(),但当然只返回 Control

【问题讨论】:

    标签: c# visual-studio localization keyboard-shortcuts


    【解决方案1】:

    Keys 枚举类型定义一个TypeConverter
    我们从KeysConverter 继承,因为这是Keys 的关联TypeConverter,我们只需要处理Keys.Oemcomma 值。

    public class ShortcutKeysConverter : KeysConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (Type.Equals(destinationType, typeof(string)) && value is Keys)
            {
                var key = (Keys)value;
    
                if (key.HasFlag(Keys.Oemcomma))
                {
                    string defaultDisplayString =
                        base
                            .ConvertTo(context, culture, value, destinationType)
                            .ToString();
    
                    return defaultDisplayString.Replace(Keys.Oemcomma.ToString(), ",");
                }
            }
    
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
    

    然后在你的Program.cs 之前调用Application.Run(...)

    TypeDescriptor
        .AddAttributes(
            typeof(Keys),
            new TypeConverterAttribute(typeof(ShortcutKeysConverter))
        );
    

    【讨论】:

      【解决方案2】:

      根据 Gabors 的回答,我解决了如下问题。它可能很老套,但它很短而且很有效。

      settingsToolStripMenuItem.ShortcutKeyDisplayString = ((new KeysConverter()).ConvertTo(Keys.Control, typeof(string))).ToString().Replace("None", ",");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-26
        • 2017-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-09
        • 2010-10-03
        • 2015-11-30
        相关资源
        最近更新 更多