HomeC&C++WainTutorialsSamplesTip&TrickTools


And now a little guide to radio-buttons. We will add a feature to the calculator, so the user can select whether he want to add or subtract the two numbers.
We create two radio buttons, just like any other button, except that we add the BS_AUTORADIOBUTTON style:
      CreateWindow("BUTTON",
                   "Add",
                   WS_CHILD | WS_VISIBLE | WS_TABSTOP |
                   BS_AUTORADIOBUTTON,
                   10, 105, 50, 14,
                   hwndDlg,
                   (HMENU )AddRadioId,
                   InstanceHandle,
                   0);
      CreateWindow("BUTTON",
                   "Sub",
                   WS_CHILD | WS_VISIBLE | WS_TABSTOP |
                   BS_AUTORADIOBUTTON,
                   65, 105, 50, 14,
                   hwndDlg,
                   (HMENU )SubRadioId,
                   InstanceHandle,
                   0);
"Add" and "Sub" is the text which will be shown next to the circle.
We can now set either of these as default, CheckDlgButton does the job:
CheckDlgButton(hwndDlg, AddRadioId, BST_CHECKED);
To indicate to the user that these radio buttons is a group, we will add a "GROUPBOX", which is a rectangle, with a text in the upper left corner. For some reason a groupbox is a button with the BS_GROUPBOX style:
      CreateWindow("BUTTON",
                   "Action",
                   WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
                   5, 85, 120, 40,
                   hwndDlg,
                   (HMENU )GroupBoxId,
                   InstanceHandle,
                   0);
For this to work you have to remove the WS_CLIPSIBLINGS and WS_CLIPCHILDREN styles when creating the main window. They are not needed so there is no harm in removing them.
To find out if a radio button is checked you can use IsDlgButtonChecked, with this we can modify our button handler:
   case WM_COMMAND:
      if(HIWORD(wParam) == BN_CLICKED &&
         LOWORD(wParam) == ButtonId)
      {
         int First = GetDlgItemInt(hwndDlg,
                                   FirstEditId,
                                   0,
                                   FALSE);
         int Second = GetDlgItemInt(hwndDlg,
                                    SecondEditId,
                                    0,
                                    FALSE);
         int Result;
         if(IsDlgButtonChecked(hwndDlg, AddRadioId))
         {
            Result = First + Second;
         }
         else
         {
            Result = First - Second;
         }
         SetDlgItemInt(hwndDlg, ResultEditId, Result, TRUE);
      }
      break;
The complete code for the application can be found here.