Skip to content

Instantly share code, notes, and snippets.

@AlexArchive
Created May 1, 2014 01:19
Show Gist options
  • Save AlexArchive/314f7f5133e2c56b454e to your computer and use it in GitHub Desktop.
Save AlexArchive/314f7f5133e2c56b454e to your computer and use it in GitHub Desktop.
HotkeyTextBox
public sealed class HotkeyTextBox : TextBox
{
public Keys Modifier { get; private set; }
public Keys Key { get; private set; }
public HotkeyTextBox()
{
Text = "None";
GotFocus += delegate { NativeMethods.HideCaret(Handle); };
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
// do not send the key data to the OS for default processing.
// we will render the key data ourselves.
//
e.Handled = true;
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
ClearHotkeyText();
return;
}
Modifier = e.Modifiers;
Key = e.KeyCode;
RenderHotkeyText();
}
private void ClearHotkeyText()
{
Modifier = Keys.None;
Key = Keys.None;
Text = "None";
}
private void RenderHotkeyText()
{
EnsureKeyIsNotModifier();
if (Modifier != Keys.None)
{
Text = Modifier.ToString().Replace(", ", " + ");
if (Key != Keys.None)
{
Text += " + " + Key;
}
return;
}
Text = Key.ToString();
}
private void EnsureKeyIsNotModifier()
{
if (Key == Keys.ControlKey ||
Key == Keys.Menu ||
Key == Keys.ShiftKey ||
Key == Keys.LWin ||
Key == Keys.RWin)
{
Key = Keys.None;
}
}
}
internal static class NativeMethods
{
[DllImport("user32.dll")]
public static extern bool HideCaret(IntPtr controlHandle);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment