To capture the tab key, catch the PreviewKeyDown event.
public static void AttachEvents<T>(T txb) where T : TextBox, ICustomTextBox {
txb.KeyDown += Txb_KeyDown;
txb.GotFocus += Txb_GotFocus;
txb.LostFocus += Txb_LostFocus;
txb.ParentChanged += Txb_ParentChanged;
txb.TextChanged += Txb_TextChanged;
txb.Enter += Txb_enter;
txb.KeyPress += Txb_KeyPress;
txb.PreviewKeyDown += Txb_PreviewKeyDown; // ■ Add
CustomNativeWindows.Add(txb, new CustomNativeWindow(txb));
}
public static void DetachEvents<T>(T txb) where T : TextBox, ICustomTextBox {
txb.KeyDown -= Txb_KeyDown;
txb.LostFocus -= Txb_LostFocus;
txb.ParentChanged -= Txb_ParentChanged;
txb.TextChanged -= Txb_TextChanged;
txb.Enter -= Txb_enter;
txb.GotFocus -= Txb_GotFocus;
txb.KeyPress -= Txb_KeyPress;
txb.PreviewKeyDown -= Txb_PreviewKeyDown; // ■ Add
// remove from dictionary
if (OriginalBackColors.ContainsKey(txb)) {
OriginalBackColors.Remove(txb);
}
if (CustomNativeWindows.TryGetValue(txb, out var customNativeWindow)) {
customNativeWindow.Dispose();
CustomNativeWindows.Remove(txb);
}
}
// ■ Add Method
private static void Txb_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
ICustomTextBox customTextBox = (ICustomTextBox)sender;
if (e.KeyData == Keys.Tab && customTextBox.Last) {
e.IsInputKey = true;
}
}
If you set the IsInputKey property of the PreviewKeyDownEventArgs class to true, you will receive a WM_KEYDOWN message in WndProc. CustomNativeWindow class as follows
case WM_KEYDOWN:
Keys keyCode = (Keys)(int)(m.WParam.ToInt64() & 0xffff);
if (keyCode == Keys.Tab) return; // ■ Add
if (Control.ModifierKeys.HasFlag(Keys.Shift)) {
switch (keyCode) {
case Keys.Up:
case Keys.Down:
case Keys.Right:
case Keys.Left:
case Keys.Home:
case Keys.End:
return;
}
}
base.WndProc(ref m);
break;
```