C#在键入时突出显示文本框中的当前字符
C# highlight current char in textbox while typing
我在单击或关注文本框选择字符时编写了这段代码突出显示
但是当我输入(编辑)突出显示时无法显示(文本框有默认文本)
textBox1.GotFocus += textbox1_OnFocus;
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
{
e.Handled = true;
}
// only allow one decimal point
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
textBox1.SelectionStart = textBox1.SelectionStart;
textBox1.SelectionLength = 1;
}
private void textbox1_OnFocus(object sender, EventArgs e)
{
textBox1.Focus();
textBox1.SelectionStart = 0 ;
textBox1.SelectionLength = 1;
}
private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
listBox1.Items.Add(textBox1.SelectionStart);
textBox1.SelectionStart = textBox1.SelectionStart;
textBox1.SelectionLength = 1;
}
我如何编辑我的代码以获得正确答案?
我写的这个很管用,但我认为这不是个好方法
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
textBox1.SelectionStart = textBox1.SelectionStart;
textBox1.SelectionLength = 1;
}
我在单击或关注文本框选择字符时编写了这段代码突出显示 但是当我输入(编辑)突出显示时无法显示(文本框有默认文本)
textBox1.GotFocus += textbox1_OnFocus;
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
{
e.Handled = true;
}
// only allow one decimal point
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
textBox1.SelectionStart = textBox1.SelectionStart;
textBox1.SelectionLength = 1;
}
private void textbox1_OnFocus(object sender, EventArgs e)
{
textBox1.Focus();
textBox1.SelectionStart = 0 ;
textBox1.SelectionLength = 1;
}
private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
listBox1.Items.Add(textBox1.SelectionStart);
textBox1.SelectionStart = textBox1.SelectionStart;
textBox1.SelectionLength = 1;
}
我如何编辑我的代码以获得正确答案?
我写的这个很管用,但我认为这不是个好方法
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
textBox1.SelectionStart = textBox1.SelectionStart;
textBox1.SelectionLength = 1;
}