Skip to content

Instantly share code, notes, and snippets.

@AlexArchive
Created August 11, 2014 11:57
Show Gist options
  • Save AlexArchive/a665687ff69d2358918a to your computer and use it in GitHub Desktop.
Save AlexArchive/a665687ff69d2358918a to your computer and use it in GitHub Desktop.
internal class HotkeyConverter : KeysConverter
{
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destination
{
if (destinationType == typeof(Keys))
{
Hotkey hotkey = (Hotkey) value;
if (hotkey != null)
{
Keys keys = Keys.None;
if (hotkey.Modifier.HasFlag(Modifiers.Alt)) keys |= Keys.Alt;
if (hotkey.Modifier.HasFlag(Modifiers.Control)) keys |= Keys.Control;
if (hotkey.Modifier.HasFlag(Modifiers.Shift)) keys |= Keys.Shift;
keys |= hotkey.Key;
return keys;
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
// this is the code that handles the Property Grid shit.
if (value is string)
{
value = base.ConvertFrom(context, culture, value);
}
// this is code that the Property Grid editor uses and the Hotkey TextBox.
if (value.GetType() == typeof (Keys))
{
Keys keys = (Keys)value;
Modifiers mods = Modifiers.None;
if (keys.HasFlag(Keys.Alt)) mods |= Modifiers.Alt;
if (keys.HasFlag(Keys.Control)) mods |= Modifiers.Control;
if (keys.HasFlag(Keys.Shift)) mods |= Modifiers.Shift;
Keys nonMods = ExtractNonMods(keys);
return new Hotkey(mods, nonMods);
}
return base.ConvertFrom(context, culture, value);
}
private static Keys ExtractNonMods(Keys keys)
{
return (Keys)((int)keys & 0x0000FFFF);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment