標籤:
滿足使用者體驗,在資料錄入時,能在輸入完一個資訊後通過斷行符號或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 }
[C#]Winform下斷行符號或Tab鍵自動切換下一個控制項焦點