ON_COMMAND_RANGE macro and multiple command buttons by thatsalok

Preface

   If you ever work in Visual Basic, it provide supports for array of button i.e. you can map several
Button to single function, but what about Visual C++ ? Is there any support for this, if yes is MFC class wizard support this and answer is YES and NO. Yeah MFC support above using
ON_COMMAND_RANGE macro! And about class wizard the answer is NO, no Class wizard don?t support ON_COMMAND_RANGE. You have to manually add function for that.

Coding:

   Now, here I will take help of simple Calculator program to make you understand how exactly ON_COMMAND_RANGE macro work.
Now design a simple user interface like this

Fig 1

   Remember one thing the id of 0 to 9 should be continuous other wise ON_COMMAND_RANGE will not work properly. If you familiar with Windows programming. The compiler maps the function to id not control. 

   Oh id by mistake you have given non continuous id to Button!. Don?t worry.
Just save your workspace and then open resource.h file and manually make them continuous! 

   Now after designing the User Interface and given id to each button, next step will be to map each control to a function. That can be easily done through Class wizard, if you don?t know where class wizard is, just right click on any control and choose class wizard option. Ok, No Map ON_CLICK Event for EQUALTO, PLUS, MINUS, MULTIPLY, DIVIDE and -/+ J.

   Now it?s time for button 0 to 9, now how to create single function who will handle these buttons. Now add a function with a UINT argument. Why?? UINT argument. This argument will bring ID of button where actual action has taken place! 

   Let your function is void OnButtonRange(UINT nID), now make a entry in your mfc MESSENGER HANDLLER so that all button get map to single function.

BEGIN_MESSAGE_MAP(CCommandRangeDlg, CDialog)!!—-Remove No Use—!1ON_COMMAND_RANGE(IDC_BUT_0,IDC_BUT_9,OnButtonRange)

END_MESSAGE_MAP()

   Now write a Small code that will display in Button ID of Clicked Button in Message Box.

void OnButtonRange(UINT nID)
{
CString szButtonId;szButtonId.Format(?Button ID := %d?,nID);MessageBox(szButtonId)}

   Now what are you waiting for just Compile and run your project and see what happening

Sample Code

   Sample Code contains the working source code of the Calculator which demonstrates use of
ON_COMMAND_RANGE. 

Special Thanks

My Mother and Father

CoderSource team

About Author

Alok Gupta is working as Software Developer In Noida,UP. You can visit his website here http://alok.bizhat.com or mail him at thatsalok#gmail.com( replace # with @)

Attachments:

   Project Files: CommandRange_sample.zip