The button "Insert" on the PC's keyboard can switch the input mode, insert and overtype. Here implement the mode "overtype" in MaskedTextBox.
private void Form1_Load(object sender, EventArgs e)
{
maskedTextBox1.Mask = "00/00/0000";
maskedTextBox1.Text = "12/21/3321";
}
private void maskedTextBox1_KeyUp(object sender, KeyEventArgs e)
{
string character = e.KeyData.ToString();
//if (e.KeyData == Keys.D0 || e.KeyData == Keys.D1 || e.KeyData == Keys.D2 || e.KeyData == Keys.D3 || e.KeyData == Keys.D4
// || e.KeyData == Keys.D5 || e.KeyData == Keys.D6 || e.KeyData == Keys.D7 || e.KeyData == Keys.D8 || e.KeyData == Keys.D9
// || e.KeyData == Keys.NumPad0 || e.KeyData == Keys.NumPad1 || e.KeyData == Keys.NumPad2 || e.KeyData == Keys.NumPad3
// || e.KeyData == Keys.NumPad4 || e.KeyData == Keys.NumPad5 || e.KeyData == Keys.NumPad6 || e.KeyData == Keys.NumPad7
// || e.KeyData == Keys.NumPad8 || e.KeyData == Keys.NumPad9)
//{
if (e.KeyValue < 58 && e.KeyValue > 47 || e.KeyValue < 106 && e.KeyValue > 95)
{
int index1 = maskedTextBox1.SelectionStart; // cursor position
if (index1 < maskedTextBox1.Text.Length)
{
string modified = maskedTextBox1.Text.Remove(index1, 1);
maskedTextBox1.Text = modified.Insert(index1, character);
if (index1 < maskedTextBox1.Text.Length - 1 && maskedTextBox1.Text[index1 + 1] == '/')
{
maskedTextBox1.SelectionStart = index1 + 2;
}
else
{
maskedTextBox1.SelectionStart = index1 + 1;
}
}
}
//}
}
When using the Chinese input method, there will be a case where KeyData is always "ProcessKey" and KeyValue is always 229.
In order to solve it, we can disable Chinese input by disabling IME.
maskedTextBox1.ImeMode = ImeMode.Disable;