Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

VB Like InputBox for MFC

0.00/5 (No votes)
14 Feb 2003 1  
InputBox for MFC without Dialog Resource.

Introduction

I have been developing softwares both in VB & VC, and like many of you, wanted to get user input using something like VB's InputBox. For this, I searched at CodeProject and found some solutions (thanx to them). The problem was: all of them used some dialog resources to solve the problem that ultimately increases the size of the application.

Solution

I am presenting the InputBox by sub-classing the MessageBox provided by MFC. Last week, I found the "Do not ask again" MessageBoxes by Nicolas Bonamy; that discusses the sub-classing of MessageBox to create a CheckBox. I used the same idea to present an EditBox to get the user input by popping the MessageBox. Thanx Nic for the idea.

Sub-classing MessageBox

This relies on MFC hooking through the AfxHookWindowCreate() function. With this, we redirect the MessageBox messages to us and therefore are able to catch (once more) WM_INITDIALOG. Here, we resize the window, add the EditBox and so on...

The big advantage is that our class is in a way the MessageBox itself with an added functionality of Edit Control; and hence the events from Edit control are handled in our class.

Using the code

To use the CInputBox, simply:

  • Add the InpuBox.h & InputBox.cpp to your project
  • Instantiate the CInputBox object
  • Call the Show method with a string.
  • When the call to Show() returns, the provided string will contain the user input.
//

CInputBox theInputBox(this);
CString strUserInput;
theInputBox.Show("Please Enter Some Text Here...", strUserInput);

  MessageBox(strUserInput);

Enhancement/Extension

I think you can further enhance the class by setting some methods to implement your specific needs like:

  • Only Numeric set ES_NUMBER
  • Special characters by catching EN_CHANGE
  • More than one Edits for different inputs.

Credits

My sincere thanx to:

  • Nicolas Bonamy: whose code inspired me for doing such an implementation.
  • My friend Sadiq: who always helps me whenever I am stuck in problems.
  • My brother Ubaid: who helped me in writing & discussing the code.
  • Most of all, my "teacher" MSDN: you know most of us are nothing without it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here