Thursday, May 1, 2008

A Custom MFC Control to Display Guitar Chords

Recently, I've tasked myself with learning a bit more about custom MFC controls. For a hands on project, I chose to create a custom MFC control for displaying guitar chords. The basic steps of creating custom MFC controls are this:

1. Create a class for your control, and inherit from a control similar to what you want to make. If nothing is similar, inherit from CStatic.
2. Override the OnPaint function to do your custom drawing.

Everything else is just MFC, although you have to be careful about redrawing. If you're constantly redrawing, you could get a bit of flicker.

To show your control in a dialog, you have do the following:

1. Add a Custom Control to the dialog.
2. Set the "Class" property of the custom control to the name of your custom class.
3. Make sure you register your custom class using the AfxRegisterClass() function. An example of this is in ChordDisplay.cpp.

In making this control, I learned something very important. If you can draw something with the CDC drawing functions, then do it that way. Bitmaps are easy enough to blit onto the Device Context, but if you need transparency or any fancy stuff, you're gonna be spending a good bit of time figuring it out (or searching for code that does what you want). I used 100% CDC drawing functions for my guitar control.

Here's a screenshot:

And, as always, my source code is here. The control can be told to draw a chord by filling a struct with some data. See ChordDatabase.cpp for more how to do that. An expansion of this would be to get a full database of chords that could be loaded from an xml file. I've only got a few chords here because it's just a sample to show the control.

No comments: