There are five essential caret functions:
CreateCaret creates a caret associated with a window.
SetCaretPos sets the position of the caret on the window.
ShowCaret shows the caret.
HideCaret hides the caret.
DestroyCaret destroys the caret.
There are also functions to get the caret position (GetCaretPos) and to get and set the caret blink time (GetCaretBlinkTime and SetCaretBlinkTime).
The caret is customarily a horizontal line, or a box that is the size of a character, or a vertical line. The vertical line is recommended when you use a proportional font such as the Windows default system font. Because the characters in a proportional font are not a fixed size, the horizontal line and box can't be set to the size of a character.
You cannot simply create a caret during the WM_CREATE message and destroy it during the WM_DESTROY message. The caret is what is known as a ”systemwide resource.“ What this means is that there is only one caret in the system. In effect, a program ”borrows“ the caret from the system when it needs to display a caret in its window.
Does this sound bizarrely restrictive? It's really not. Think about it: The display of a caret in a window makes sense only when the window has the input focus. This indicates to the user that he or she may enter text in the program. Only one window has the input focus at any time so only one caret is needed in the whole system.
A program can determine if it has the input focus by processing the WM_SETFOCUS and WM_KILLFOCUS messages. A window procedure receives a WM_SETFOCUS message when it receives the input focus, and a WM_KILLFOCUS message when it loses the input focus. These messages occur in pairs: A window procedure will always receive a WM_SETFOCUS message before it receives a WM_KILLFOCUS message, and it always receives an equal number of WM_SETFOCUS and WM_KILLFOCUS messages over the course of the window's lifetime.
The main rule for using the caret is simple: A window procedure calls CreateCaret during the WM_SETFOCUS message and DestroyCaret during the WM_KILLFOCUS message.
There are a few other rules: The caret is created hidden. After calling CreateCaret, the window procedure must call ShowCaret for the caret to be visible. In addition, the window procedure must hide the caret by calling HideCaret whenever it draws something on its window during a message other than WM_PAINT. After it finishes drawing on the window, it calls ShowCaret to display the caret again. The effect of HideCaret is additive: If you call HideCaret several times without calling ShowCaret, you must call ShowCaret the same number of times before the caret becomes visible again.