C#文本框光标定位

10

我觉得我可能只是缺少一个简单的属性,但你能否将光标设置到文本框中某行的末尾?

private void txtNumbersOnly_KeyPress(object sender, KeyPressEventArgs e)
{
   if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b' || e.KeyChar == '.' || e.KeyChar == '-')
   {
      TextBox t = (TextBox)sender;
      bool bHandled = false;
      _sCurrentTemp += e.KeyChar;

      if (_sCurrentTemp.Length > 0 && e.KeyChar == '-')
      {
         // '-' only allowed as first char
         bHandled = true;
      }

      if (_sCurrentTemp.StartsWith(Convert.ToString('.')))
      {
         // add '0' in front of decimal point
         t.Text = string.Empty;
         t.Text = '0' + _sCurrentTemp;
         _sCurrentTemp = t.Text; 
         bHandled  = true;
      }

      e.Handled = bHandled;
   }

在以'.'作为第一个字符进行测试后,光标会放在所添加的文本之前。因此,即使没有手动移动光标,结果也会变成"1230."而不是"0.123"。

如果这是一个重复的问题,我也向您道歉。

5个回答

22
t.SelectionStart = t.Text.Length;

3

在 WPF 中,您应该使用:

textBox.Select(textBox.Text.Length,0);

0代表没有选择任何字符。


2
假设您使用的是WinForms而不是WPF...
void SetToEndOfLine(TextBox tb, int line)
{
   int loc = 0;
   for (int x = 0; x < tb.Lines.Length && tb <= line; x++)
   {
      loc += tb.Lines[x].Length;
   }
   tb.SelectionStart = loc;
}

2

在文本框上设置SelectionStart属性可以控制光标的位置。


1
这将是有用的。
        private void textBox_TextChanged(object sender, EventArgs e)
    {
        string c = "";
        string d = "0123456789.";
        foreach (char a in textBox.Text)
        {
            if (d.Contains(a))
                c += a;
        }
        textBox.Text = c;
        textBox.SelectionStart = textBox.Text.Length;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接