private void txtNumber_KeyPress(object sender, KeyPressEventArgs e)
{
TextBox tb = sender as TextBox;
// 允許:數字鍵(48-57)、退格鍵(8)、小數點(.)
// 限制:只能有一個小數點
if (e.KeyChar == '.' && tb.Text.IndexOf('.') >= 0)
{
e.Handled = true; return;
}
if (!((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == '.' || e.KeyChar == '\b'))
{
e.Handled = true;
}
}
設計器屬性窗口 → 事件 → KeyPress → 選擇 txtNumber_KeyPress,或代碼綁定:
this.txtNumber.KeyPress += txtNumber_KeyPress;
if (e.KeyChar == '-' && tb.SelectionStart == 0 && !tb.Text.Contains("-"))
return; // 允許開頭輸入負號
MaskedTextBox:設置 Mask="999.99" 等格式。NumericUpDown:純整數/小數增減控件。PreviewTextInput + 正則驗證。