C#在键入时突出显示文本框中的当前字符

时间:2017-06-25 10:23:18

标签: c# char highlight

我在单击或关注文本框选择字符时突出显示此代码 但是当我输入(编辑)高亮显示不能显示(文本框有默认文本)

        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;
    }

如何编辑我的代码才能得到正确答案?

1 个答案:

答案 0 :(得分:0)

我写这个有用,但我认为这不是好方法

        private void textBox1_KeyUp(object sender, KeyEventArgs e)
    {
        textBox1.SelectionStart = textBox1.SelectionStart;
        textBox1.SelectionLength = 1;
    }