Ghost
Ghost

Reputation: 1835

How to put a button in an MFC application?

My mfc program draws the following shape in the client area- now i want to place a button next to this for rearrangement of the shape.

enter image description here

I know i can use a toolbar or a menu button, but is there a way i can place a button right next to the box? something like this:

enter image description here

Upvotes: 2

Views: 16827

Answers (2)

GazTheDestroyer
GazTheDestroyer

Reputation: 21241

All you need to do is create a CButton, and position it appropriately.

//.h
#define MYBUTTONID 10000 //or whatever doesn't conflict with your existing resources

public class CMyVew : public CView
{
    CButton m_Button;

    virtual void OnInitialUpdate();
    void RepositionButton();
}

//.cpp
void CMyVew::OnInitialUpdate()
{
   //this creates the actual button GUI window
   m_Button.Create("Rearrange", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, CRect(0,0,0,0), this, MYBUTTONID);
   RepositionButton();
}

void CMyVew::RepositionButton()
{
    //work out button position you need
    m_Button.MoveWindow(x, y, width, height);
}

Note that the button is only created once and takes care of drawing itself. You do not need to worry about it in OnDraw() or anything like that.

The only time you need to worry is when the button should move position. This is why I separated out the RepositionButton() function. For instance, if you are using a CScrollView and the user scrolls, the button window has no knowledge of this, so you will need to react to scroll events and call RepositionButton()

You can react to the button's messages just like you would any other button by adding an ON_BTN_CLICKED message map.

Upvotes: 6

Richard Chambers
Richard Chambers

Reputation: 17573

You can create your own buttons by using the Windows API. The main thing is to get the window handle of your client area and then using that as the parent handle when creating your buttons.

For instance here is an example of the use of the Windows API to create a button.

The Create() method is part of the CWnd class.

CRect windRect (xColumn, xRow, xColumn +  nWidth, xRow + nHeight);
Create (_T("BUTTON"), myCaption, WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_MULTILINE, windRect, pParentWnd, m_myId);

You will need to know how wide and tall to make the button as well as an identifier. The id is needed so that you can find it on the parent window and also process messages from button actions.

Take a look at the Windows API documentation on CreateWindow.

Upvotes: 1

Related Questions