Thursday, March 8, 2007

How to Create a Button or Edit box at runtime?


(P.S :- Create all these in the ………..Dlg.h and …………..Dlg.cpp only)

First create an object for the button or edit box you want to create.

If you want a button create a object for the CButton class or else for a edit box create it from CEdit and likewise.

A sample code snippet is shown below;

CButton *pButton;

CEdit *pEdit;

Then in the Constructor

Add the following lines of code

pButton = new CButton;

pEdit = new CEdit;

In the Init Method call the Create member function and pass the necessary parameters.

Its code snippet is shown below.

pButton->Create("My Button",

WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON ,

CRect(10, 10, 100, 30),

this,

IDC_BUTTON1

);

pEdit->Create( WS_CHILD| WS_VISIBLE, CRect(50,50,150,80), this, 3 );

And thus your Button is created.

Now you have to make it active to user input.

You have to create an ID for it and capture its messages through message maps.

For that you have to do the following.

In the file named (resource.h) add the control id. Below is a code snippet to do it.

#define IDC_BUTTON1 2000

#define IDC_EDIT1 3

If you want your control to accept the user button you have to add to the message map.

For that do the following

In the file named (……Dlg.cpp) -> Go to Message Map Definition and add the following code snippet

ON_BN_CLICKED(IDC_BUTTON2, OnButton2)

In ON_BN_CLICKED, the BN denotes Button and CLICKED denotes click event. You can also add other message handlers.

Then in the file name (………Dlg.h) add the following code snippet

afx_msg void OnButton2();

The void OnButton2(); is the function where we tell the Button what to do when a click event as occurred.

Then in file named (………..Dlg.cpp) define the function,

Sample of a function is shown below.

void CCreateDialog1Dlg::OnButton2()

{

MessageBox("Button 2 is clicked");

}

Here we just make the Message Box pop-up once the button is clicked.

No comments:

Post a Comment