這是一個?C# 輸入對話框函數,主要功能包括:
-
基礎功能:創建帶標題、提示文本和輸入框的對話框,返回用戶輸入或空字符串(取消時)
-
增強特性:
- 支持必填項驗證
- 支持正則表達式格式驗證
- 實時錯誤提示與按鈕狀態更新
- 自定義驗證失敗消息
- 自動資源管理(using 語句)
-
用戶體驗:
- Enter/Esc 快捷鍵支持
- 輸入有效性實時反饋
- 提交時強制格式檢查
-
代碼質量:
- 模塊化驗證邏輯
- 事件驅動設計
- 安全的資源釋放機制
/// <summary>
/// 創建一個可配置的輸入對話框,提示用戶輸入文本并返回結果
/// </summary>
/// <param name="prompt">顯示給用戶的提示文本</param>
/// <param name="title">對話框的標題(可選,默認為空)</param>
/// <param name="defaultValue">輸入框的默認值(可選,默認為空)</param>
/// <param name="isRequired">是否為必填項(可選,默認否)</param>
/// <param name="validationPattern">正則驗證模式(可選,默認不驗證)</param>
/// <param name="validationMessage">驗證失敗時的提示(可選)</param>
/// <returns>用戶輸入的文本,如果用戶取消則返回空字符串</returns>
public static string InputBox(string prompt, string title = "", string defaultValue = "",bool isRequired = false,string validationPattern = "",string validationMessage = "輸入格式不正確")
{using (Form form = new Form())using (Label label = new Label())using (TextBox textBox = new TextBox())using (Button buttonOk = new Button())using (Button buttonCancel = new Button())using (ErrorProvider errorProvider = new ErrorProvider()){// 配置窗體屬性form.Text = title;form.ClientSize = new Size(350, 160);form.FormBorderStyle = FormBorderStyle.FixedDialog;form.StartPosition = FormStartPosition.CenterScreen;form.MinimizeBox = false;form.MaximizeBox = false;form.AcceptButton = buttonOk;form.CancelButton = buttonCancel;form.KeyPreview = true;form.FormClosing += (sender, e) => {if (form.DialogResult == DialogResult.OK && !IsValidInput(textBox.Text)){e.Cancel = true;MessageBox.Show(validationMessage, "輸入錯誤", MessageBoxButtons.OK, MessageBoxIcon.Warning);}};// 配置提示標簽label.Text = prompt;label.Location = new Point(15, 20);label.AutoSize = true;// 配置文本輸入框textBox.Text = defaultValue;textBox.Location = new Point(15, 85);textBox.Size = new Size(310, 20);textBox.TextChanged += (sender, e) => {errorProvider.Clear();if (isRequired && string.IsNullOrWhiteSpace(textBox.Text)){errorProvider.SetError(textBox, "此字段為必填項");}};// 配置確定按鈕buttonOk.Text = "確定";buttonOk.Location = new Point(100, 120);buttonOk.DialogResult = DialogResult.OK;buttonOk.Enabled = !isRequired || !string.IsNullOrWhiteSpace(defaultValue);// 配置取消按鈕buttonCancel.Text = "取消";buttonCancel.Location = new Point(180, 120);buttonCancel.DialogResult = DialogResult.Cancel;// 添加控件到窗體form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel });// 輸入驗證方法bool IsValidInput(string input){if (isRequired && string.IsNullOrWhiteSpace(input))return false;if (!string.IsNullOrEmpty(validationPattern) && !System.Text.RegularExpressions.Regex.IsMatch(input, validationPattern))return false;return true;}// 啟用實時驗證textBox.TextChanged += (sender, e) => {buttonOk.Enabled = IsValidInput(textBox.Text);};// 顯示對話框并返回結果return form.ShowDialog() == DialogResult.OK ? textBox.Text : "";}
}
示例調用:
// 簡單文本輸入
string name = InputBox("請輸入姓名");// 帶驗證的郵箱輸入
string email = InputBox("郵箱", "注冊", isRequired:true, validationPattern:@"^[\w-]+@[\w-]+\.[a-z]{2,}$");