テキスト ボックスにControl.KeyPressイベント ハンドラを追加します。
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)) //bypass control keys
{
int dotIndex = textBox1.Text.IndexOf('.');
if (char.IsDigit(e.KeyChar)) //ensure it's a digit
{ //we cannot accept another digit if
if (dotIndex != -1 && //there is already a dot and
//dot is to the left from the cursor position and
dotIndex < textBox1.SelectionStart &&
//there're already 2 symbols to the right from the dot
textBox1.Text.Substring(dotIndex + 1).Length >= 2)
{
e.Handled = true;
}
}
else //we cannot accept this char if
e.Handled = e.KeyChar != '.' || //it's not a dot or
//there is already a dot in the text or
dotIndex != -1 ||
//text is empty or
textBox1.Text.Length == 0 ||
//there are more than 2 symbols from cursor position
//to the end of the text
textBox1.SelectionStart + 2 < textBox1.Text.Length;
}
}
次のように、デザイナーまたはコンストラクターで行うことができます。
public Form1()
{
InitializeComponent();
//..other initialization
textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
}
また、テキストの最後だけでなく、任意の位置に数字を挿入できるように、いくつかのチェックを追加しました。ドットと同じ。ドットから右に 2 桁を超えないように制御します。TextBox.SelectionStart プロパティを使用して、テキスト ボックス内のカーソルの位置を取得しました。詳細については、このスレッドを確認してください:テキストボックス内のカーソルの位置を見つけるにはどうすればよいですか?