Category Archives: Uncategorized

Codexpert – 2015 Articles Summary

Microsoft Libraries and C++ Programming Language

What’s next?

We planned to continue the Direct2D/DirectWrite series but also other articles about programming with C++ using Microsoft Windows libraries like MFC, ATL, Windows API and so on.

See also

Codexpert – 2014 Articles Summary

Microsoft Libraries

C++ Language

Windows Tips

See also

Codexpert – 2013 Articles Summary

C++ Language and STL

Microsoft Libraries (Windows API, MFC, ATL, WIC, WMI, etc.)



Painting the Dialog Backround

Generally, it’s not necessary to change the dialog’s default background. Besides, if have to display an image in a dialog, it is preferable to do it in a child control (e.g. static picture or custom control). However, let’s say that’s a requirement or we want to do it as an exercise or just for fun.

Painting the Dialog Background

Painting the Dialog Background

The image shows a dialog that has its background painted with a fancy brush. It also has a nice Earth image, transparently painted directly in the dialog’s client area.
Let’s see how to make it!.

Handling WM_ERASEBKGND message

This example handles the WM_ERASEBKGND message and fills the background by using a custom brush.  Finally, it returns TRUE to prevent further erasing.

Next’ we would notice that’s necessary to handle WM_CTLCOLOR in order to change also the beackground of some child controls (static, radio buttons, etc.). As long as, WM_CTLCOLOR allows also changing the dialog’s background, we can get rid of previous method and do all the work in the WM_CTLCOLOR message handler.

Handling WM_CTLCOLOR message

To change the default background as well as other attributes, WM_CTLCOLOR message handler (OnCtlColor) must return a not-NULL brush handle.

Note: In Win32, WM_CTLCOLOR notification message was replaced by WM_CTLCOLORDLG, WM_CTLCOLORSTATIC, and so on. However, MFC still keeps WM_CTLCOLOR for 16-bit legacy code compatibility. The third argument (nCtlColor) of OnCtlColor handler function, helps us to decide if in fact has been received one of the following notifications: WM_CTLCOLORDLG, WM_CTLCOLORSTATIC, etc.

Handling WM_PAINT message

Finally, let’s “paint the Earth”! As in any other kind of window, the right place to perform paining is the WM_PAINT message handler.

Demo project

Download the demo project and you can find more implementation details.


See also

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.

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

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.


  • 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.


Custom Draw vs. Owner Draw Controls

While most of Windows developers heard about and eventually used owner-draw controls, fewer know about custom-draw controls. Both types of controls allow customization but they are pretty different. So let’s have a quick look at each one.

Owner Draw Controls

An owner-draw control is a common Windows control that have a special owner-draw style set.

  • BS_OWNERDRAW for button controls;
  • LVS_OWNERDRAWFIXED for listview controls;
  • and so on…

Once the owner-draw style is set, the “owner” has the whole drawing responsibility. For that purpose, have to handle WM_DRAWITEM notification (sent to parent window) and perform drawing. In MFC, can also handle WM_DRAWITEM reflected message in the control’s MFC class or override DrawItem virtual function, if available.
Additionally, in some cases can handle WM_MEASUREITEM, to modify the size of control items. See also WM_COMPAREITEM and WM_DELETEITEM which also can be useful when developing  owner-draw controls.
You can see how owner-draw controls are made by having a look, for example, in the implementation of CBitmapButton and CCheckListBox MFC classes.

Custom Draw Controls

Custom-draw controls have no special style. We say that a control is custom-draw if handles the NM_CUSTOMDRAW notification (sent via WM_NOTIFY message). This case, there is no necessary for the “owner” to perform the whole drawing, but can change some defaults. For example, can tell the system to fill an item with some custom color or perform some additional drawing after the default drawing has been done.
Here is an example of custom-draw listvew control, having alternate item colors and a selection rectangle around a particular subitem.

Custom-Draw Listview Control

Custom-Draw Listview Control


See also

C++11 concurrency: locks

In a previous post I introduced the C++11 support for threads. In this article I will discuss the locking features provided by the standard that one can use to synchronize access to shared resources.

The core syncing primitive is the mutex, which comes in four flavors, in the <mutex> header:

  • mutex: provides the core lock() and unlock() and the non-blocking try_lock() method that returns if the mutex is not available.
  • recursive_mutex: allows multiple acquisitions of the mutex from the same thread.
  • timed_mutex: similar to mutex, but it comes with two more methods try_lock_for() and try_lock_until() that try to acquire the mutex for a period of time or until a moment in time is reached.
  • recursive_timed_mutex: is a combination of timed_mutex and recusive_mutex.

Here is a simple example of using a mutex to sync the access to the std::cout shared object.

In the next example we’re creating a simple thread-safe container (that just uses std::vector internally) that has methods like add() and addrange(), with the later implemented by calling the first.

Running this program results in a deadlock.

The reason for the deadlock is that the tread that own the mutex cannot re-acquire the mutex, and such an attempt results in a deadlock. That’s were recursive_mutex come into picture. It allows a thread to acquire the same mutext multiple times. The maximum number of times is not specified, but if that number is reached, calling lock would throw a std::system_error. Therefore to fix this implementation (apart from changing the implementation of addrange not to call lock and unlock) is to replace the mutex with a recursive_mutex.

Then the output looks something like this:

Notice the same numbers are generated in each call to func(). That is because the seed is thread local, and the call to srand() only initializes the seed from the main thread. In the other worker threads it doesn’t get initialized, and therefore you get the same numbers every time.

Explicit locking and unlocking can lead to problems, such as forgetting to unlock or incorrect order of locks acquiring that can generate deadlocks. The standard provides several classes and functions to help with this problems.

The wrapper classes allow consistent use of the mutexes in a RAII-style with auto locking and unlocking within the scope of a block. These wrappers are:

  • lock_guard: when the object is constructed it attempts to acquire ownership of the mutex (by calling lock()) and when the object is destructed it automatically releases the mutex (by calling unlock()). This is a non-copyable class.
  • unique_lock: is a general purpose mutex wrapper that unlike lock_quard also provides support for deferred locking, time locking, recursive locking, transfer of lock ownership and use of condition variables. This is also a non-copyable class, but it is moveable.

With these wrappers we can rewrite the container class like this:

Notice that attempting to call try_lock_for() or try_lock_until() on a unique_lock that wraps a non-timed mutex results in a compiling error.

The constructors of these wrapper guards have overloads that take an argument indicating the locking strategy. The available strategies are:

  • defer_lock of type defer_lock_t: do not acquire ownership of the mutex
  • try_to_lock of type try_to_lock_t: try to acquire ownership of the mutex without blocking
  • adopt_lock of type adopt_lock_t: assume the calling thread already has ownership of the mutex

These strategies are declared like this:

Apart from these wrappers for mutexes, the standard also provides a couple of methods for locking one or more mutexes.

  • lock: locks the mutexes using a deadlock avoiding algorithm (by using calls to lock(), try_lock() and unlock()).
  • try_lock: tries to call the mutexes by calling try_lock() in the order of which mutexes were specified.

Here is an example of a deadlock case: we have a container of elements and we have a function exchange() that swaps one element from a container into the other container. To be thread-safe, this function synchronizes the access to the two containers, by acquiring a mutex associated with each container.

Suppose this function is called from two different threads, from the first, an element is removed from container 1 and added to container 2, and in the second it is removed from container 2 and added to container 1. This can lead to a deadblock (if the thread context switches from one thread to another just after acquiring the first lock).

To fix the problem, you can use std::lock that guaranties the locks are acquired in a deadlock-free way:

Hopefully this walktrough will help you understand the basics of the synchronization functionality supported in C++11.