繁体   English   中英

在 C# Windows 中更改文本框中的光标位置

[英]Change cursor position in textbox in C# Windows

我有一个加载 MDI 子 winform 的 winform。 子winform中的所有文本框始终将光标停留在左侧,我无法将其移动到另一个位置,除非我选择所有文本并重新输入。 如何启用此功能以使光标可以使用鼠标停留在任何位置?

在以下示例中,光标将定位在表单的每个文本框中的第二个字符之后。 焦点将位于最后一个,但通过反复按 TAB 键,您可以验证是否已为每个文本框设置了光标位置。

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

试试这个,希望对你有帮助;)

//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 Input Right to Left testex with '##.####' mask 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;           
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM