How to get the localized keyboard-key-name in VS C#

≯℡__Kan透↙ 提交于 2019-12-12 03:47:30

问题


I have a ToolStripMenuItem that has the ShortcutKeys Ctrl+Oemcomma (i.e. Ctrl+,). I want to show that shortcut near the item-name, so the user can see that shortcut. Unluckily it's shown as Ctrl+Oemcomma and not as the more understandable Ctrl+,.

There's the property ShortcutKeyDisplayString that overrides the automatic created string, so that way one can fix it. But as soon as the application is run in a language that doesn't call the control-key Ctrl (e.g. in germany it's called Strg), that ShortcutKeyDisplayString looks wrong, as all other automatic created shortcut-descriptions are translated (i.e. if in an english OS a description is displayed as Ctrl+S, in a german OS it then displays Strg+S).

Is there a function that returns the localized name of a key so that I could use that to set the ShortcutKeyDisplayString? I.e. I'm looking for a function that returns Ctrl in an english OS and Strg in a german OS etc. I tried System.Windows.Forms.Keys.Control.ToString(), but that of course just returns Control.


回答1:


Define a TypeConverter for Keys enum type.
We inherit from KeysConverter as this is the associated TypeConverter of Keys and we need to handle only the Keys.Oemcomma value.

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

Then in your Program.cs before callign Application.Run(...):

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



回答2:


Based on Gabors answer I solved it as follows. It might be hacky but it's short and works.

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


来源:https://stackoverflow.com/questions/37100079/how-to-get-the-localized-keyboard-key-name-in-vs-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!