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

在测试“。”之后 作为第一个字符,光标位于添加的文本之前。因此,结果不是“0.123”,而是“1230”。不用自己移动光标。

如果这是一个重复的问题,我也很抱歉。

4

5 回答 5

22
t.SelectionStart = t.Text.Length;
于 2010-05-04T17:06:49.057 回答
3

在 WPF 中你应该使用:

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

其中 0 是选择的字符数

于 2013-06-27T13:30:06.353 回答
2

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

于 2010-05-04T17:00:49.517 回答
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;
}
于 2010-05-04T17:02:07.570 回答
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;
    }
于 2015-10-21T16:50:28.710 回答