[C#]Winform下回车或Tab键自动切换下一个控件焦点

时间:2023-03-09 01:28:10
[C#]Winform下回车或Tab键自动切换下一个控件焦点

满足用户体验,在数据录入时,能在输入完一个信息后通过回车或Tab键自动的切换到下一个控件(字段).

在界面控件设计时,默认可以通过设置控件的TabIndex来实现.但在布局调整时或者是对输入的内容有选择性时,从用代码的方式来处理显得更好维护一点.

完整的实现方法如下:

/// <summary>
/// 回车、Tab键盘切换或执行操作
/// </summary>
public sealed class TabEnter:IDisposable
{
private List<StringBuilder> ml;
private int i=0;
private System.Windows.Forms.Control mc;
/// <summary>
/// 知否启用Tab键功能
/// </summary>
private bool mallowTab=false;
/// <summary>
/// 是否启用Tab键切换/执行.
/// </summary>
public bool AllowTab
{
get { return mallowTab; }
set { mallowTab = value; }
}
public TabEnter(System.Windows.Forms.Control c)
{
ml = new List<StringBuilder>();
mc = c;
}
public TabEnter(System.Windows.Forms.Control c, bool allowTab):this(c)
{
mallowTab = allowTab;
}
public void Add(System.Windows.Forms.Control c)
{
c.KeyPress += KeyPressHandler;
c.TabIndex = i;
ml.Add(new StringBuilder(c.Name));
i += 1;
}
/// <summary>
/// 在需要独立处理KeyPress时间时,采用KeyUp来执行,当然可继续实现KeyDown
/// </summary>
/// <param name="c"></param>
public void AddKeyUp(System.Windows.Forms.Control c)
{
c.KeyUp += KeyUpHandler;
c.TabIndex = i;
ml.Add(new StringBuilder(c.Name));
i += 1;
}
private void KeyPressHandler(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if ((e.KeyChar == (Char)13) || (e.KeyChar == (Char)9 && mallowTab == true))
{
int j = ((System.Windows.Forms.Control)sender).TabIndex;
if (j >= ml.Count - 1) return;
string cname = ml[j + 1].ToString();
if (string.IsNullOrEmpty(cname)) return;
System.Windows.Forms.Control[] tca = mc.Controls.Find(cname, true);
if (tca == null || tca.Length == 0) return;
System.Windows.Forms.Control tc = tca[0];
if (tc == null) return;
System.Windows.Forms.Button b = tc as System.Windows.Forms.Button;
if (b != null)
b.PerformClick();
else
tc.Focus();
}
}
private void KeyUpHandler(Object sender, System.Windows.Forms.KeyEventArgs e)
{
if ((e.KeyCode == System.Windows.Forms.Keys.Enter) || (e.KeyCode == System.Windows.Forms.Keys.Tab && mallowTab == true))
{
int j = ((System.Windows.Forms.Control)sender).TabIndex;
if (j >= ml.Count - 1) return;
string cname = ml[j + 1].ToString();
if (string.IsNullOrEmpty(cname)) return;
System.Windows.Forms.Control[] tca = mc.Controls.Find(cname, true);
if (tca == null || tca.Length == 0) return;
System.Windows.Forms.Control tc = tca[0];
if (tc == null) return;
if (tc.GetType()==typeof(System.Windows.Forms.Button))
{
((System.Windows.Forms.Button)tc).PerformClick();
}
else
{
if (tc.Visible == true) tc.Focus();
} }
}
#region "资源释放"
public void Dispose()
{
Disposing(true);
GC.SuppressFinalize(this);
}
private bool m_disposed = false;
protected void Disposing(bool disposing)
{
if (!m_disposed)
{
if (disposing)
{
//Release managed resources
ml.Clear();
ml = null;
i = 0;
mc = null;
}
//Release unmanaged Resources
m_disposed = true;
}
} ~TabEnter()
{
Disposing(false);
}
#endregion
}