码迷,mamicode.com
首页 > Windows程序 > 详细

C#/VB.NET Winform程序自定义输入光标

时间:2014-07-01 14:15:31      阅读:312      评论:0      收藏:0      [点我收藏+]

标签:des   winform   http   使用   width   os   

本文转载自真有意思网(http://www.zu14.cn)

作者:三角猫 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);
        }
    }
}

C#/VB.NET Winform程序自定义输入光标,布布扣,bubuko.com

C#/VB.NET Winform程序自定义输入光标

标签:des   winform   http   使用   width   os   

原文地址:http://www.cnblogs.com/qingtianhua/p/3818090.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!