Carets for Custom Controls
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:
static extern bool CreateCaret(IntPtr hWnd, int hBitmap, int nWidth, int nHeight);
static extern bool SetCaretPos(int X, int Y);
static extern bool ShowCaret(IntPtr hWnd);
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);
private void Form1_Deactivate(object sender, EventArgs e)
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.