Color Picker Listview Control

Among other common Windows dialogs we can find Color Dialog Box that allows to pick a color for our purposes. It can simply be created by a call of ChooseColor WinAPI function or, if using MFC, with the help of CColorDialog class.
Also, the MFC versions shipped with Visual Studio 2008 or newer, include CMFCColorDialog class which shows a little bit more fancy color selection dialog.

However, let’s say we have to make our own custom color picker control (let’s say, looking similar tho one used in Photoshop). Beside making a custom or ActiveX control from scratch, a faster approach is to customize the Windows listview (“SysListView32“) control, kept in MFC by CListCtrl class. There are two ways to customize a listview control: making it custom-draw or making it owner-draw.

Custom Draw Color Picker Listview

Color Picker Listview (custom-draw)

Color Picker Listview (custom-draw)

First we have to handle NM_CUSTOMDRAW notification, sent via WM_NOTIFY.
In subitem pre-paint phase, we can indicate which color has to be used to paint whatever list subitem.
Example

Finally, hadle NM_CLICK notification, get the color of the clicked item and send a user message to the parent.
Example

This method is pretty simple but it has a disadvantage: we cannot modify item/subitem height. So, if this is necessary we gave to make an owner-draw listview control.

Owner Draw Color Picker Listview

Color Picker Listview (owner-draw)

Color Picker Listview (owner-draw)

An owner-draw listview control must have LVS_OWNERDRAWFIXED style set (“Owner Draw Fixed” property must be set to “True” in the resource editor).
Next, we can handle WM_MEASUREITEM to set item size and override CListCtrl::DrawItem in order to perform custom drawing. Just to note: would be necessary to map by hand the WM_MEASUREITEM message; also DrawItem isn’t called for each subitem.
Example

Notes

  • Implementation details can be found in the attached demo projects
  • The color pickers presented here are just draft versions intended to demonstrate how to do. You can further improve them by adding new features like loading a custom color palette, adding custom colors on the fly, and so on.
  • A brief presentation of custom-draw and owner draw controls, can be found in this article: Custom Draw vs. Owner Draw Controls.

Downloads

Leave a Reply