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

2019-09-16 06:40发布

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.

2条回答
成全新的幸福
2楼-- · 2019-09-16 07:05

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", ",");
查看更多
一纸荒年 Trace。
3楼-- · 2019-09-16 07:10

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))
    );
查看更多
登录 后发表回答