本文转载自真有意思网(http://www.zu14.cn)
作者:三角猫 DeltaCat
摘要:C#/VB.NET Winform程序自定义输入光标的实现,我们可以通过调用Windows 提供的一套对输入光标进行控制的API进行操作......
作者:三角猫 DeltaCat
摘要:C#/VB.NET Winform程序自定义输入光标的实现,我们可以通过调用Windows 提供的一套对输入光标进行控制的API进行操作......
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);
}
}
}