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

标签 c# winforms mouse-cursor

我有一个加载 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);
  }
}

关于c# - 在 C# Windows 中更改文本框中的光标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8206723/

相关文章:

c# - HttpWebRequest .GetResponse 抛出 WebException 'The operation has timed out'

c# - datagridview 单元格编辑和保存 Windows 窗体中的功能?

c# - Datagrid 在滚动后选择了错误的行

javascript - 如何将对象列表从 View 中的 javascript 代码传递到 Controller 中的操作方法

c# - Azure 事件中心 : checkpoint best practices in C# EventProcessorClient

java - 为特定的 JTable 单元格设置鼠标光标

c# - 到处隐藏光标

html - 光标 :pointer on hover html5 canvas element

c# - 在 64 位机器上基于 AnyCPU 与 x64 平台构建的 C# 应用程序的性能

c# - 如何防止控件在模式窗体打开时捕获 KeyDown 事件?