I have a CheckedListBox. I would like to be able to select items when I click on the text but check/uncheck them when I click on the checkbox area on the left. If I set CheckOnClick then the items are checked and unchecked whenever I click, even on the text, so that's no good. But if I clear CheckOnClick then I have to click twice to check and uncheck.
My first thought is to handle MouseClick or MouseDown events and call IndexFromPoint to find out which row is clicked. Then I would just guess that the checkbox is on the left, from x=position from 0 to, say, ItemRectangle.Height. Depending on the distance from the left, I could select or check/uncheck.
The question is whether there is a better way to determine if the mouse is over the checkbox or over the text. Different styles could have different sized checkboxes and might put them on the left, right, etc...
Here is the actual code (from .Net Reference Source) that paints the checkboxes, in the
DrawItem
event:EDIT: Here is
CheckBoxRenderer.ConvertFromButtonState
:}
I wrote this and it seems to work, thanks to SLaks. To use this, CheckOnClick must be true and CheckInCheckbox as well. Inherit from CheckedListbox.
The idea is to figure out where the checkbox is and, if the click is outside of the checkbox, to set the checkstate to its opposite. Later, when the mouseclick is received by the base class, CheckedListbox, it will again change the checkbox state back to what it was.
A little hacky changing the state back and forth but I couldn't find any other way to get around the way that CheckedListbox uses SelectedIndex to check/uncheck, which is sort of a hack, too.