Skip to content

Carets for Custom Controls

5 June 2008

I decided to start posting in English (at least the technical posts). I hope this way I can reach more people who might be interested in the things I blog about (the .NET Framework, C#, compilers and such).

Today I was thinking about developing a custom control that receives text input. But how am I supposed to display the caret? I searched the Internet for some .NET controls that do the same thing and the best I got was a separate thread used only for blinking a custom drawn caret. That seemed a bit strange – are all WinForm controls implemented that way?

I decided to go to the source – how does WinAPI go about drawing them? Well, pretty simple – there are a bunch of functions in user32.dll. I imported some of them:

[DllImport("user32.dll")]
static extern bool CreateCaret(IntPtr hWnd, int hBitmap, int nWidth, int nHeight);

[DllImport("user32.dll")]
static extern bool SetCaretPos(int X, int Y);

[DllImport("user32.dll")]
static extern bool ShowCaret(IntPtr hWnd);

[DllImport("user32.dll")]
static extern bool DestroyCaret();

From here on, things are pretty simple. One thing to note though, MSDN clearly states that there is only one caret created per message queue – that is, you can’t have two different carets blinking at the same time in different controls (or the same control for that matter). So, to add a custom caret to the form itself, I just handled the Activated and Deactivated events:

private void Form1_Activated(object sender, EventArgs e)
{
    CreateCaret(this.Handle, 1, 5, 10);
    SetCaretPos(0, 0);
    ShowCaret(this.Handle);
}

private void Form1_Deactivate(object sender, EventArgs e)
{
    DestroyCaret();
}

The argument 1 for hBitmap will give it the neat appearance – more about it on MSDN. This example is very basic but I think it’s a good starting point.

From → code complete

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: