Created
May 1, 2014 01:19
-
-
Save AlexArchive/314f7f5133e2c56b454e to your computer and use it in GitHub Desktop.
HotkeyTextBox
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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