如何使用当用户进入文本框时,光标颜色改变C#

时间:2015-02-09 17:52:05

标签: winforms cursor

我有一个小问题,我使用winforms,我有一个想法,我想在用户编辑它时将光标颜色更改为textBox。这个想法是在用户写作时显示一种颜色,显示一个没有显示光标的颜色。如何将颜色光标更改为texBox? 谢谢你的回答。

1 个答案:

答案 0 :(得分:1)

从WinForms

中的一个文本框更改光标
  1. 添加类NativeMethod

    public class NativeMethod {
    
    [DllImport("user32.dll")]
    public extern static int GetCaretBlinkTime();
    [DllImport("user32.dll")]
    public extern static int SetCaretBlinkTime(int wMSeconds);
    [DllImport("user32.Dll")]
    public extern static int GetCaretPos(ref POINT pt);
    [DllImport("user32.dll")]
    public extern static int SetCaretPos(int x, int y);
    [DllImport("user32.Dll")]
    public extern static int DestroyCaret();
    [DllImport("user32.dll")]
    public extern static int CreateCaret(IntPtr hwnd, IntPtr hBitmap, int nWidth, int nHeight);
    [DllImport("user32.dll")]
    public extern static int ShowCaret(IntPtr hwnd);
    [DllImport("user32.dll")]
    public extern static int HideCaret(IntPtr hwnd);
    
    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int x;
        public int y;
    }
    

    }

  2. 创建变量:

    private System.Drawing.Bitmap bm; private IntPtr hBitmap;
    
  3. 从TextBox添加Click和TextChanged方法,自定义光标将显示在这些方法中,必须添加以下几行:

    NativeMethod.CreateCaret(this.textBox1.Handle, hBitmap, 0, 0);
    
    NativeMethod.ShowCaret(this.textBox1.Handle);
    
  4. 各自的方法如下:

    private void textBox1_Click(object sender, EventArgs e)
    {
        NativeMethod.CreateCaret(this.textBox1.Handle, hBitmap, 0, 0);
        NativeMethod.ShowCaret(this.textBox1.Handle);
    }
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        NativeMethod.CreateCaret(this.textBox1.Handle, hBitmap, 0, 0);
        NativeMethod.ShowCaret(this.textBox1.Handle);
    }
    
  5. 在Form_Load事件中添加下一行。

    bm = new Bitmap("puntero.png");
    hBitmap = bm.GetHbitmap();
    
  6. “puntero.png”是先前创建的图像,尺寸可能会有所不同,但在我们使用px尺寸图像5X25红色的示例中,此图像为负色。