Visual – MFC – RadioButton – Checked , GetCheckedRadioButton – C++

Publicado: 13 de março de 2014 em C/C++

Diferentemente das linguagens baseadas no Microsoft Framework, o MFC utiliza C++ nativo e trabalha direto no conceito do sistema operacional Windows manipulando mensagens diretamente das APIs do Windows, portanto o que é muito simples como  programar em uma linguagem de alto nível, aqui fica um pouco diferente e um pouco mais complicado, é o caso de verificar o simples status de um Checkbox ou um Radiobutton.

RadioButton

Em computação, um botão de opção ou botão de rádio (Radiobutton) é um elemento de interface gráfica (isto é um componente widget) com dois estados: selecionado (ativado) e não-selecionado (desativado), quando o usuário pressiona um botão do mouse ou uma tecla como Espaço. Botões de opção são usados num grupo para apresentar um conjunto limitado de escolhas (duas ou mais) que são mutuamente exclusivas. Deste maneira, quando o usuário seleciona um outro botão no mesmo conjunto, o outro botão já selecionado torna-se automaticamente desativado.

GetCheckedRadioButton

É uma função que retorna um valor equivalente ao Checked (marcado) em linguagens de alto nível, neste caso recupera o ID do botão de opção atualmente verificado no grupo especificado e retorna o ID do botão de opção marcada, ou 0 se nenhum for selecionado.

Visual Studio

Escolha um novo projeto MFC Application, e marque Dialog Based, em Design Time, apague os componentes default e coloque um 3 StaticTexts, 4 Radiobuttons, 3 EditsControl e um botão. Mude as propriedades de um EditControl para Multiline = true, Read Only = true e Vertical Scroll = true. Use a imagem abaixo para referencia do design.

radiobutton_design

Aqui levamos em consideração que você já sabe como usar as variáveis para os componentes e como criar seus respectivos eventos, caso ainda não saiba veja nosso primeiro post MFC. Crie as variáveis como na imagem abaixo:

radiobutton_var

Crie os eventos BN_CLICKED para cada RadioButton e  para o botão. Use o código abaixo para completar o código gerado automaticamente, seu programa deve apresentar o seguinte resultado:

radiobutton_exe

Exemplo:

Neste exemplo criamos um grupo de botões de radio que efetua as 4 operações básicas da matemática, usando o evento de item e a verificação do seu estado.

C++


// RadioBDlg.cpp : implementation file
//

#include "stdafx.h"
#include "RadioB.h"
#include "RadioBDlg.h"
#include "afxdialogex.h"
#include "Windowsx.h"
#include <assert.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CAboutDlg dialog used for App About

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()

// CRadioBDlg dialog

CRadioBDlg::CRadioBDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CRadioBDlg::IDD, pParent)

{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CRadioBDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_EDIT1, campo1);
	DDX_Control(pDX, IDC_EDIT2, campo2);
	DDX_Control(pDX, IDC_BUTTON1, botao);
	DDX_Control(pDX, IDC_EDIT3, texto);
}

BEGIN_MESSAGE_MAP(CRadioBDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_RADIO1, &CRadioBDlg::OnBnClickedRadio1)
ON_BN_CLICKED(IDC_RADIO2, &CRadioBDlg::OnBnClickedRadio2)
ON_BN_CLICKED(IDC_RADIO3, &CRadioBDlg::OnBnClickedRadio3)
ON_BN_CLICKED(IDC_RADIO4, &CRadioBDlg::OnBnClickedRadio4)
ON_BN_CLICKED(IDC_BUTTON1, &CRadioBDlg::OnBnClickedButton1)
END_MESSAGE_MAP()

// CRadioBDlg message handlers

BOOL CRadioBDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CRadioBDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CRadioBDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CRadioBDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

/**

  Nosso Código começa Aqui

  **/

// Evento on click do RadioButton - Append menssagem

void CRadioBDlg::OnBnClickedRadio1()
{

		int tam = texto.GetWindowTextLengthW();
		texto.SetSel(tam, tam);
		texto.ReplaceSel(L"Somar:\n");

}

void CRadioBDlg::OnBnClickedRadio2()
{

	int tam = texto.GetWindowTextLengthW();
	texto.SetSel(tam, tam);
	texto.ReplaceSel(L"Subtrair:\n");
}

void CRadioBDlg::OnBnClickedRadio3()
{

	int tam = texto.GetWindowTextLengthW();
	texto.SetSel(tam, tam);
	texto.ReplaceSel(L"Multiplicar:\n");
}

void CRadioBDlg::OnBnClickedRadio4()
{

	int tam = texto.GetWindowTextLengthW();
	texto.SetSel(tam, tam);
	texto.ReplaceSel(L"Dividir:\n");
}

// Evento On Click do Botão -- Efetua o calculo

void CRadioBDlg::OnBnClickedButton1()
{

	CString valor1;
	CString valor2;
	CString dTOstr;
	double total;

	//Captura valor dos TextControls
	campo1.GetWindowTextW(valor1);
	campo2.GetWindowTextW(valor2);

	// Verifica qual RadioButton esta checado
	int RadioStatus = GetCheckedRadioButton(IDC_RADIO1, IDC_RADIO4);

		switch (RadioStatus)
		{
		case IDC_RADIO1:
			{

				total = _wtof(valor1) + _wtof(valor2);
				dTOstr.Format(_T("%2.f"), total);
				int tam = texto.GetWindowTextLengthW();
				texto.SetSel(tam, tam);
				texto.ReplaceSel(valor1 + L" + " + valor2 + L" = " + dTOstr + L"\n");
			}
			break;

			case IDC_RADIO2:
			{

				total = _wtof(valor1) - _wtof(valor2);
				dTOstr.Format(_T("%2.f"), total);
				int tam = texto.GetWindowTextLengthW();
				texto.SetSel(tam, tam);
				texto.ReplaceSel(valor1 + L" - " + valor2 + L" = " + dTOstr + L"\n");
			}
				break;

			case IDC_RADIO3:
			{

				total = _wtof(valor1) * _wtof(valor2);
				dTOstr.Format(_T("%2.f"), total);
				int tam = texto.GetWindowTextLengthW();
				texto.SetSel(tam, tam);
				texto.ReplaceSel(valor1 + L" * " + valor2 + L" = " + dTOstr + L"\n");
			}
				break;

			case IDC_RADIO4:
			{

				total = _wtof(valor1) / _wtof(valor2);
				dTOstr.Format(_T("%2.f"), total);
				int tam = texto.GetWindowTextLengthW();
				texto.SetSel(tam, tam);
				texto.ReplaceSel(valor1 + L" / " + valor2 + L" = " + dTOstr + L"\n");
			}
				break;
		}

}

Publicidade

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair /  Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair /  Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair /  Alterar )

Conectando a %s