[英]C# textbox cursor positioning
我觉得我只是缺少一个简单的属性,但是你可以将光标设置到文本框中一行的末尾吗?
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;
}
在测试'。'之后 作为第一个char,光标位于添加的文本之前。 因此,而不是“0.123”,结果是“1230”。 没有自己移动光标。
如果这是一个重复的问题,我也会道歉。
t.SelectionStart = t.Text.Length;
在WPF中你应该使用:
textBox.Select(textBox.Text.Length,0);
其中0是选择的字符数
在文本框上设置SelectionStart
属性将控制光标位置。
假设您使用的是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;
}
这将很有用。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.