在C#Windows中更改文本框中的光标位置 [英] Change cursor position in textbox in C# Windows

查看:262
本文介绍了在C#Windows中更改文本框中的光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个加载MDI子Winform的Winform。子Winform中的所有文本框始终将光标停留在左侧,除了选择所有文本并重新输入外,我无法将其移至其他位置。我该如何启用它以使光标可以使用鼠标停留在任何位置?

I have a winform which load MDI child winform. All textboxs in child winform always have cursor stay at left side and I can't move it to another position, except I choose all text and re-input. How can I enable this to make cursor can stay at any position by using mouse?

推荐答案

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

In the following example the cursor will be positioned after the second character in each textbox of the form. The focus will be on the last one, but by pressing the TAB key repeatedly, you can verify that the cursor position has been set for every textbox.

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

这篇关于在C#Windows中更改文本框中的光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆