自定义光标样式

搞了两天,终于把自定义光标搞定了:

下面是参考资料

Windows 提供了一套对输入光标进行控制的API, 包括:CreateCaret,SetCaretPos,DestroyCaret,ShowCaret,HideCaret。这些API的定义如下:

[DllImport("user32.dll")]
static extern bool CreateCaret(IntPtr hWnd, IntPtr hBitmap, int nWidth, int nHeight);
[DllImport("user32.dll")]
static extern bool ShowCaret(IntPtr hWnd);
[DllImport("User32.dll")]
static extern bool HideCaret(IntPtr hWnd);
[DllImport("User32.dll")]
static extern bool SetCaretPos(int x, int y);
[DllImport("user32.dll")]
static extern bool DestroyCaret();上面的 CreateCaret 中的参数以此为

hWnd : 要自定义输入光标的控件的句柄
hBitmap : 如果使用图片作为输入光标,则是图片的句柄;否则: 0 表示使用黑色的光标色,1表示使用灰色的光标色
nWidth:   光标的宽度
nHeight: 光标的高度
我们下面举个例子,假设:我们有个输入框textBox2,让这个输入的框的光标变成黑色的小块

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace CustomCaret
{
    /// <summary>
    /// 自定义输入光标的演示
    /// 作者: 三角猫
    /// 网址: http://www.zu14.cn/
    /// 转载请保留此信息
    /// </summary>
    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);
        [DllImport("User32.dll")]
        static extern bool HideCaret(IntPtr hWnd);
        [DllImport("User32.dll")]
        static extern bool SetCaretPos(int x, int y);
        [DllImport("user32.dll")]
        static extern bool DestroyCaret();

        public Form1()
        {
            InitializeComponent();
            //为输入框绑定光标变化的处理事件
             this.textBox2.GotFocus += new EventHandler(textBox2_GotFocus);
            this.textBox2.LostFocus += new EventHandler(textBox2_LostFocus);
        }

        void textBox2_LostFocus(object sender, EventArgs e)
        {
            HideCaret(this.textBox2.Handle);
            DestroyCaret();
        }

        void textBox2_GotFocus(object sender, EventArgs e)
        {
            CreateCaret(textBox2.Handle, IntPtr.Zero, 10, textBox2.Height);
            ShowCaret(textBox2.Handle);
        }
    }
}

我做的也和上面的差不多的原理,不过要自定义图片,还是得创建Bitmap(BMP格式的图片),长宽参考自身控件大小(很重要,笔者就是因为这个一个下午的时间没有了),制作一张等长宽的图片

图片颜色要反过来,比如要显示黑色线,就要用黑色背景,白色线,在显示的时候,就变成黑色线了

代码主要改动是CreateCaret(textBox2.Handle, IntPtr.Zero, 10, textBox2.Height);

改成

Bitmap bm = new Bitmap("图片路径")

CreateCaret(textBox2.Handle, bm.GetHbitmap(), 0,0);

提示:

如果是Dev的XtraGrid 则先用End事件和lose事件 ,先在事件中拿到TextEidt对象,然后用上述方法

原文地址:https://www.cnblogs.com/linyijia/p/2229933.html