MFC Radio Button Control Example

Radiobuttons can be created with one of the following styles
BS_RADIOBUTTON – checking and unchecking are done manually
BS_AUTORADIOBUTTON – checking and unchecking are done automatically. When clicked, a radio button checks itself and unchecks the other radio buttons in the group.

The ON_BN_CLICKED macro maps the button click function to the button click event

#include <afxwin.h>
#define ID_REDBUTTON 1000
#define ID_GREENBUTTON 1001
#define ID_BLUEBUTTON 1002
class CSimpleApp : public CWinApp
{
public:
BOOL InitInstance();
};

class CMainFrame : public CFrameWnd
{
public:
CMainFrame();
afx_msg void wRedButtonOnClick( );
afx_msg void wGreenButtonOnClick( );
afx_msg void wBlueButtonOnClick( );
afx_msg void OnPaint();
DECLARE_MESSAGE_MAP()

//instantiate button class;
CButton wRedButton;
CButton wGreenButton;
CButton wBlueButton;
CButton wGroupBox;
COLORREF wcolor;
HBRUSH OnCtlColor(CDC *,CWnd *,UINT );
bool OnEraseBkgnd(CDC *);
};

BOOL CSimpleApp::InitInstance()
{
m_pMainWnd = new CMainFrame();
m_pMainWnd->ShowWindow(m_nCmdShow);
return TRUE;
}

CMainFrame::CMainFrame()
{
Create(NULL,TEXT("Radio Button Demo MFC"), WS_OVERLAPPEDWINDOW ,CRect(25,25,410,200));
wcolor=RGB(255,255,255);
wGroupBox.Create(TEXT("Select"),BS_GROUPBOX | WS_CHILD | WS_VISIBLE , CRect(50,25,300,100), this, ID_REDBUTTON);
wRedButton.Create(TEXT("Red"),BS_AUTORADIOBUTTON | WS_CHILD | WS_VISIBLE | WS_BORDER, CRect(70,50,125,75), this, ID_REDBUTTON);
wGreenButton.Create(TEXT("Green"),BS_AUTORADIOBUTTON |WS_CHILD | WS_VISIBLE | WS_BORDER , CRect(135,50,210,75), this, ID_GREENBUTTON);
wBlueButton.Create(TEXT("Blue"),BS_AUTORADIOBUTTON | WS_CHILD | WS_VISIBLE | WS_BORDER , CRect(220,50,275,75), this, ID_BLUEBUTTON);
}

BEGIN_MESSAGE_MAP(CMainFrame,CFrameWnd)
//message map
ON_BN_CLICKED(ID_REDBUTTON,wRedButtonOnClick)
ON_BN_CLICKED(ID_GREENBUTTON,wGreenButtonOnClick)
ON_BN_CLICKED(ID_BLUEBUTTON,wBlueButtonOnClick)
ON_WM_PAINT()
END_MESSAGE_MAP()

CSimpleApp MFCApp1;

afx_msg void CMainFrame::wRedButtonOnClick()
{

//red button click function
wcolor=RGB(255,0,0);
Invalidate();
}

//green button click function
afx_msg void CMainFrame::wGreenButtonOnClick()
{
wcolor=RGB(0,255,0);
Invalidate();
}

//blue button click function
afx_msg void CMainFrame::wBlueButtonOnClick()
{
wcolor=RGB(0,0,255);
Invalidate();
}

afx_msg void CMainFrame::OnPaint()
{
CPaintDC paintDC(this);
CRect rect;
GetClientRect(&rect);
paintDC.FillSolidRect(&rect,wcolor);
}