简体   繁体   中英

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

I have a ToolStripMenuItem that has the ShortcutKeys Ctrl+Oemcomma (ie 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 (eg in germany it's called Strg ), that ShortcutKeyDisplayString looks wrong, as all other automatic created shortcut-descriptions are translated (ie 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? Ie 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 .

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

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", ",");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM