Avoiding GetDlgItem in MFC

Introduction

When you learned to program Windows in C, you learned about GetDlgItem. This is the way to get a handle for a control when you are working with a dialog. In C, it is the only way to get a window handle for the control. In C++/MFC, there is a better way. It makes about as much sense to use GetDlgItem in C++/MFC as it does to program Windows in assembly code. Yes, I know there are masochists who like to program Windows in assembly code. But it is rare that it is actually needed. Perhaps in the inner loop of a DSP algorithm, where you might drop a few of those fancy Pentium III opcodes inline, but the rest of the time it is insanity. The same is true of GetDlgItem. Actually, there is slightly more reason to use a raw GetDlgItem than there is to use assembly code, but the reasons represent rare and very uncommon cases.

My view is, if you are writing more than one GetDlgItem per year, you are probably not using C++/MFC correctly. Fortunately, there is a better, more elegant, and safer way to get access to controls using MFC.

Note that you should almost never use UpdateData in a dialog. If you use it, you should use it only in a modeless dialog. There is, as far as I can tell, absolutely no excuse for using UpdateData in a modal dialog. I discuss this in much more detail in another essay. But the techniques shown here are fundamental to avoiding the use of UpdateData as well. A simple rule: If you're calling UpdateData in a modal dialog, you're not using MFC correctly.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Better train people and risk they leave – than do nothing and risk they stay.” - Anonymous