表單開發中常需「標籤 + 輸入框」固定組合,且需支援:
lblField (Label):字段名,可選隱藏lblValue (Label):瀏覽模式顯示值,繪製底線txtValue (TextBox):編輯模式輸入,初始隱藏置於 lblValue 後timer (Timer):解決焦點切換時機問題lblValue.MouseDown → 隱藏 Label、顯示 TextBox、複製文字、聚焦;txtValue.Leave → 反向切換、更新 Label 文字。UseSystemPasswordChar 為 true 時,離開編輯模式顯示 "Secret"。OnPaint 中用 Graphics.DrawLine 畫底線,根據字段名是否顯示調整 X 起點與寬度。Anchor 屬性 + OnPaint 動態計算 Location/Width。public string UText { get => txtValue.Text; set { lblValue.Text = txtValue.Text = value; } }
public bool ReadOnly { get => txtValue.ReadOnly; set => txtValue.ReadOnly = value; }
public bool UserSystemPasswordChar { get => txtValue.UseSystemPasswordChar; set => txtValue.UseSystemPasswordChar = value; }
public Color LineColor { get => lineColor; set { lineColor = value; Invalidate(); } }
public string LBLText { get => lblField.Text; set => lblField.Text = value; }
public event EventHandler UTextChanged;
public event EventHandler UDoubleClick;
private void txtValue_TextChanged(object s, EventArgs e) => UTextChanged?.Invoke(s, e);
private void txtValue_DoubleClick(object s, EventArgs e) => UDoubleClick?.Invoke(s, e);
拖放控件到表單,屬性視窗設置 LBLText、LineColor、UserSystemPasswordChar 等,即可獲得統一風格的輸入項。