In Shark Xu's article, two attributes are added to all controls to enable the return key to automatically jump to the next Control. This provides us with a method to press the return key or up/down key in a Windows application, automatically jumps between input items. It solves a lot of problems and reduces the amount of code. Honyoung proposed to solve this problem by sending a Tab event. This simplifies the process of setting two properties (especially when setting the next or last control, it is prone to errors ). At the same time, the TabIndex attribute is provided in VS. NET, which easily leads to a mismatch between the ControlFocus attribute and the TabIndex. So on the basis of Shark Xu, I implemented the following code: "add and send a keyboard event Tab event to all controls to automatically jump to the next Control by using the Enter key:
Using System;
Using System. ComponentModel;
Using System. Diagnostics;
Using System. Text;
Using System. Windows. Forms;
Using System. Collections;
Namespace sxu
{
[ProvideProperty ("AllowKeyTab", typeof (Component)]
Public partial class KeyTab: Component, IExtenderProvider
{
Public Keys NextK;
Public Keys previusk;
Hashtable _ hashTable = new Hashtable ();
Constructor # region Constructor
Public KeyTab ()
{
InitializeComponent ();
}
Public KeyTab (IContainer container)
{
Container. Add (this );
InitializeComponent ();
}
# Endregion
Attribute AllowKeyTab # region attribute AllowKeyTab
Public void SetAllowKeyTab (Component component, bool Allow)
{
If (Allow)
{
If (_ hashTable. Contains (component )! = True)
{
// MessageBox. Show (component. ToString ());
_ HashTable. Add (component, Allow );
Control currentC = (Control) component;
CurrentC. KeyDown + = new KeyEventHandler (currentC_KeyDown );
}
}
Else
{
If (_ hashTable. Contains (component) = true)
{
_ HashTable. Remove (component );
}
}
}
Public bool GetAllowKeyTab (Component component)
{
If (_ hashTable. Contains (component ))
{
Return true;
}
Return false;
}
# Endregion
/** // <Summary>
/// Used for Attribute search
/// </Summary>
/// <Param name = "component"> </param>
/// <Returns> </returns>
Public bool GetKeyTab (Component component)
{
If (_ hashTable. Contains (component ))
{
Return (bool) _ hashTable [component];
}
Return false;
}
Private void currentC_KeyDown (object sender, KeyEventArgs e)
{
If (e. KeyCode = this. NextK)
{
SendKeys. Send ("{TAB }");
}
Else if (e. KeyCode = this. previusk)
{
SendKeys. Send ("+ {TAB}"); // Send shift + tab
}
}
Public bool CanExtend (object component)
{
// The extension is supported only when it is a common control (discharged Form ).
If (component is Control &&! (Component is Form ))
{
Return true;
}
Return false;
}
}
}
Add the following code to Form:
Private void Form1_Load (object sender, EventArgs e)
{
This. keyTab1.NextK = Keys. Down;
This. keytab1.previusk = Keys. Up;
}
Download the program code