自定义光标样式
搞了兩天,終于把自定義光標搞定了:
下面是參考資料
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對象,然后用上述方法
總結
- 上一篇: Android应用程序线程消息循环模型分
- 下一篇: crontab 用法