我有一个加载MDI子窗体的WinForm。子窗体中所有文本框的光标始终停留在左侧,我无法将其移动到其他位置,除非选择所有文本并重新输入。
如何启用此功能以使鼠标可以使光标停留在任何位置?
我有一个加载MDI子窗体的WinForm。子窗体中所有文本框的光标始终停留在左侧,我无法将其移动到其他位置,除非选择所有文本并重新输入。
如何启用此功能以使鼠标可以使光标停留在任何位置?
using System;
using System.Windows.Forms;
public class Program
{
public static void Main()
{
var form = new Form();
form.Text = "Cursor Positioning Test";
form.Visible = true;
form.Shown += delegate(object sender, EventArgs args) {
foreach (var control in form.Controls)
{
var textBox = control as TextBox;
if (textBox != null)
{
textBox.Focus();
textBox.SelectionStart = 2;
textBox.SelectionLength = 0;
}
}
};
var textBox1 = new TextBox();
textBox1.Text = "hello";
textBox1.Left = 10;
textBox1.Top = 10;
form.Controls.Add(textBox1);
var textBox2 = new TextBox();
textBox2.Text = "stack";
textBox2.Left = 10;
textBox2.Top = 10 + textBox1.Height + 10;
form.Controls.Add(textBox2);
var textBox3 = new TextBox();
textBox3.Text = "overflow";
textBox3.Left = 10;
textBox3.Top = 10 + textBox1.Height + 10 + textBox2.Height + 10;
form.Controls.Add(textBox3);
Application.Run(form);
}
}
var button = new Button(); form.Controls.Add(button);
),(2)将 form.Shown
事件处理程序委托更改为 foreach (TextBox textBox in form.Controls) { textBox.Focus(); textBox.SelectionStart = 2; textBox.SelectionLength = 0; }
。后者会引发我上面提到的异常。 - kol试一下这个,希望对你有所帮助;)
//if you want put cusror at the end of text use this:
TextBox1.SelectionStart = TextBox1.Text.Length;
TextBox1.SelectionLength = 0;
//use this for custom location int CustomIndex
TextBox1.SelectionStart = CustomIndex;
TextBox1.SelectionLength = 0;
//这是一个关于Windows表单中带有'##.####'掩码的maskedTextBox从右到左输入测试,其为decimal(6,4)类型的内容。
private void maskedTextBoxMaskRTF_KeyPress(object sender, KeyPressEventArgs e) {
var maskedTextBox = (MaskedTextBox)sender;
var contLit = maskedTextBox.Text.Where(ch => ".,".Contains(ch)).Count();
var value = maskedTextBox.Text.Replace(".", "").Replace(",", "") + e.KeyChar;
if (value.Length >= maskedTextBox.Mask.Length - contLit)
value = value.Substring(1);
else
while (value.Length < maskedTextBox.Mask.Length - contLit)
value = "_" + value;
maskedTextBox.Text = value;
maskedTextBox.SelectionStart = maskedTextBox.Mask.Length - 1;
maskedTextBox.SelectionLength = 1;
}
foreach (var c in form.Controls)
迭代其元素,使用TextBox tb = c as TextBox; if (tb != null) ...
测试当前控件是否为 TextBox,并为tb
设置光标位置。 - kol