Home > MFC, Windows API > When to use OnDrawItem, DrawItem and OnPaint?

When to use OnDrawItem, DrawItem and OnPaint?

Note: This post assumes that owner draw flag for controls is set.

OnDrawItem is mainly provided to facilitate owner drawing child controls in a parent window class without sub classing them. An e.g. can be a tab/button/listbox/combobox/menu control, we can ownerdraw these without sub classing using this function. Note that OnDrawItem is called as result of the event WM_DRAWITEM which is sent to the owner window of an owner-drawn button, combo box, list box, or menu when a visual aspect of the button, combo box, list box, or menu has changed.

Signature of OnDrawItem is as follows, nIDCtl points to the ID of the controls that’s meant to owner drawn. So here you will get the id of your tab control in nIDCtl and you can owner draw it here.

afx_msg void OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct);

There is another option, that’s by sub classing and overriding DrawItem virtual function. Note that DrawItem get’s called by OnDrawItem.

Stack trace to DrawItem virtual member function is as follows…

CListBoxEx::DrawItem(tagDRAWITEMSTRUCT * 0x0012f6d4) line 20
CListBox::OnChildNotify(unsigned int 43, unsigned int 1000, long 1242836, long * 0x00000000) line 125
CWnd::SendChildNotifyLastMsg(long * 0x00000000) line 2683
CWnd::ReflectLastMsg(HWND__ * 0x0004089a, long * 0x00000000) line 2721
CWnd::OnDrawItem(int 1000, tagDRAWITEMSTRUCT * 0x0012f6d4) line 1156 + 14 bytes
CLearnDrawingDlg::OnDrawItem(int 1000, tagDRAWITEMSTRUCT * 0x0012f6d4) line 46
CWnd::OnWndMsg(unsigned int 43, unsigned int 1000, long 1242836, long * 0x0012f4f0) line 1930

DrawItem messages makes things easier for developers, we get OD flags that tells which action requires painting.

  1. ODS_CHECKED
  2. ODS_FOCUS
  3. ODS_DISABLED.
  4. etc

We just have to do the painting stuff.

But if we are going via OnPaint then we are on our own, we’ve got to find out when an item is selected, when it’s in focus, when it’s disabled based on every paint event that we get. Maybe even scrolling too. So that’s for the tough guys. 😉

So basically for quick and easy painting things we go via OnDrawItem, or DrawItem else for full control use OnPaint.

Quickest way to owner draw would be to use OnDrawItem.

Advertisements
Categories: MFC, Windows API Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: