在 C# 中更改文本框中的插入符(光标)

Change Caret (Cursor) in Textbox in C#

我想更改 C# 文本框中的插入符号,使其看起来更宽,就像在旧 DOS 应用程序中一样。

我有:

举例我想要的:

我试过了:

using System.Runtime.InteropServices;

...

  [DllImport("user32.dll")]
  static extern bool CreateCaret(IntPtr hWnd, IntPtr hBitmap, int nWidth, int nHeight);
  [DllImport("user32.dll")]
  static extern bool ShowCaret(IntPtr hWnd);

...

public partial class Form1 : Form
{
    [DllImport("user32.dll")]
    static extern bool CreateCaret(IntPtr hWnd, IntPtr hBitmap, int nWidth, int nHeight);
    [DllImport("user32.dll")]
    static extern bool ShowCaret(IntPtr hWnd);

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Shown(object sender, EventArgs e)
    {
        CreateCaret(textBox1.Handle, IntPtr.Zero, 20, textBox1.Height);
        ShowCaret(textBox1.Handle);
    }
}

但看起来还是一样。你能帮忙的话,我会很高兴。提前致谢!

编辑:

这只是一个例子。我的真实代码如下:

TextBox textbox = new TextBox();
 textbox.MaxLength = fieldLength;
 textbox.Width = fieldLength*24;
 textbox.MaxLength = maxChars;
 this.Controls.Add(textbox);

 CreateCaret(textbox.Handle, IntPtr.Zero, 20, textbox.Height);
 ShowCaret(textbox.Handle);

代码被调用但没有改变任何东西。

编辑 2:

我试过这个例子,它工作正常,但我的问题仍然存在: 创建文本框时我无法更改插入符。它只适用于使用表单创建的文本框。

你没有正确link事件,你应该更改为:

public partial class Form1 : Form
{
    [DllImport("user32.dll")]
    static extern bool CreateCaret(IntPtr hWnd, IntPtr hBitmap, int nWidth, int nHeight);
    [DllImport("user32.dll")]
    static extern bool ShowCaret(IntPtr hWnd);

    public Form1()
    {
        InitializeComponent();
        this.Shown += Form1_Shown;
    }

    private void Form1_Shown(object sender, EventArgs e)
    {
        CreateCaret(textBox1.Handle, IntPtr.Zero, 20, textBox1.Height);
        ShowCaret(textBox1.Handle);
    }
}

发生的事情似乎是显示的事件只会在最初起作用。当您通过 Tab 键离开文本框并返回控件时,插入符号将由底层代码重置。

查看 this 主题中的答案。

我借鉴了他们的DrawDaret Method,稍微改了一下。在 textbox1.Enter 事件上调用 DrawCaret 不起作用。文本框实现可能会通知 Enter 事件,然后更改插入符号。这将撤消在 Enter 事件处理程序中对插入符号所做的更改。

编辑

但是该控件还有一个 GotFocus 事件,您可以使用它。

public partial class Form1 : Form
{
    [DllImport("user32.dll")]
    static extern bool CreateCaret(IntPtr hWnd, IntPtr hBitmap, int nWidth, int nHeight);
    [DllImport("user32.dll")]
    static extern bool ShowCaret(IntPtr hWnd);

    public Form1()
    {
        InitializeComponent();

        textBox1.GotFocus += new EventHandler(textBox1_GotFocus);
    }

    void textBox1_GotFocus(object sender, EventArgs e)
    {
        DrawCaret(textBox1);
    }

    public void DrawCaret(Control ctrl)
    {
        var nHeight = 0;
        var nWidth = 10;

        nHeight = Font.Height;

        CreateCaret(ctrl.Handle, IntPtr.Zero, nWidth, nHeight);
        ShowCaret(ctrl.Handle);
    }
}