The TVS_CHECKBOXES style is quirky, which is a polite way of saying that it is crazy
A customer was having trouble with tree view checkboxes.
We have a tree view control in a dialog box. It is defined like this:CONTROL "", IDC_TREEVIEW, WC_TREEVIEW, TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT | TVS_DISABLEDRAGDROP | TBS_SHOWSELALWAYS | TVS_CHECKBOXES | WS_BORDER | WS_HSCROLL | WS_TABSTOP, 65, 22, 259, 182
As you can see, the
CHECKBOXESstyle is set in the dialog template. When the dialog is created, but before it is shown, we have code that populates the tree. At that time, we want to set the checked state of some of the nodes by using the
SetCheckStatemacro. If we call
GetCheckStateimmediately after setting the checked state, it reports the checked state correctly. However, once the tree view finishes rendering, all of the check boxes are cleared.
Curiously, if we hide the dialog box, then set the check boxes, and then show the dialog box, then the check boxes are not reset.
Why can’t we check the tree view items immediately upon adding them, but before the dialog is shown for the first time? And more importantly, is there a workaround?
The tree view control’s handling of the
CHECKBOXES style is quirky.
“Quirky” is a polite word for “crazy”.
If you want to use this style, you must set the TVS_
CHECKBOXESstyle with SetWindowLong after you create the treeview control, and before you populate the tree. Otherwise, the checkboxes might appear unchecked, depending on timing issues.
Tree view check boxes were poorly-designed. But we’re stuck with them.
The customer confirmed that removing the
CHECKBOXES style from the dialog template and instead applying the style at run time fixes the problem.
CHECKBOXES style is quirky because it was bolted on rather than designed in. We’ll spend the next several days exploring its quirks and trying to come up with a set of best practices for its use.