IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)

API Windows en C

Le contrôle ComboBox ou liste déroulante

Article lu   fois.

L'auteur

Profil ProSite personnel

Liens sociaux

Viadeo Twitter Facebook Share on Google+   

I. Introduction

Vous connaissez la liste déroulante, appelée aussi Combobox. C'est un champ d'édition associé à une liste de choix. Comme la liste de choix, elle sert à faire un choix parmi plusieurs, et selon son style elle peut être éditable ou non.
Afin de l'implémenter, nous reprendrons l'exemple de la liste de choix, ou nous la remplacerons par une liste déroulante.

Image non disponible

II. Mise en œuvre

Le contrôle liste déroulante sera ajouté depuis les ressources et identifié par la constante ID_CB1. Elle aura le style CBS_DROPDOWNLIST (déroulante non éditable).

 
Sélectionnez
    COMBOBOX ID_CB1, 20, 24, 56, 45, CBS_DROPDOWNLIST

Comme pour l'exemple de la liste de choix, les valeurs de la propriété figure seront définies à l'aide de constante et mémorisées dans la variable Forme.

 
Sélectionnez
#define ID_CARRE 0
#define ID_CERCLE 1
#define ID_TRIANGLE 2

UINT Forme;
Initialisation des données :
    switch (uMsg)
    {
      case WM_INITDIALOG:
         {
          SendDlgItemMessage(hDlg, ID_CB1, CB_ADDSTRING, 0, (LONG)"Carré");
          SendDlgItemMessage(hDlg, ID_CB1, CB_ADDSTRING, 0, (LONG)"Cercle");
          SendDlgItemMessage(hDlg, ID_CB1, CB_ADDSTRING, 0, (LONG)"Triangle");
          SendDlgItemMessage(hDlg, ID_CB1, CB_SETCURSEL, Forme, 0);

          return TRUE;
         }

Nous remplissons la liste déroulante avec les chaînes de caractères représentant les divers choix possibles. Ceci en envoyant à la liste déroulante, des messages CB_ADDSTRING avec un pointeur sur la chaîne en question comme paramètre lParam du message. Les messages seront envoyés avec la fonction SendDlgItemMessage. Puis nous sélectionnons l'option de la liste déroulante correspondant à la figure actuelle en lui envoyant un message CB_SETCURSEL avec l'index de la sélection actuelle comme paramètre wParam du message (index mémorisé dans la variable globale Forme). Les index dans les listes déroulantes commençant par la valeur 0.

Récupération du choix :

 
Sélectionnez
      case WM_COMMAND :
         if (LOWORD(wParam) == IDOK )
                {
                   Forme = SendDlgItemMessage(hDlg, ID_CB1, CB_GETCURSEL, 0, 0);

                   EndDialog(hDlg,DB_OK);
                   return TRUE;
                }

Pour récupérer la sélection que l'utilisateur a choisie dans la liste déroulante nous lui envoyons un message CB_GETCURSEL avec la fonction SendDlgItemMessage, la valeur de l'index étant retournée par cette fonction.


Le reste du code est identique à l'exemple de la liste de choix.

III. Code complet

resource.h :

 
Sélectionnez
#define IDM_QUIT  1
#define IDM_PROP 2

#define ID_RB1 101
#define ID_RB2 102
#define ID_RB3 103    

#define ID_CB1 201

resource.rc :

 
Sélectionnez
#include <windows.h>

#include "resource.h"

LEMENU MENU
BEGIN
  POPUP "Fichier"
    BEGIN
       MENUITEM "Propriétés...", IDM_PROP
       MENUITEM SEPARATOR
       MENUITEM "Quitter", IDM_QUIT
    END
END

DIALOG1 DIALOG
    110, 0, 175, 100
          STYLE WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
                                               CAPTION "Propriétés de la figure"
BEGIN
    LTEXT "Figure", -1, 35, 10, 30, 10 WS_GROUP
    COMBOBOX ID_CB1, 20, 24, 56, 45, CBS_DROPDOWNLIST

    GROUPBOX " Trait ", -1, 96, 10, 60 , 60, WS_GROUP
    AUTORADIOBUTTON "Fin", ID_RB1, 106, 20, 40, 15
    AUTORADIOBUTTON "Moyen", ID_RB2, 106, 35, 40, 15
    AUTORADIOBUTTON "Large", ID_RB3, 106, 50, 40, 15

    DEFPUSHBUTTON "OK", IDOK, 36, 77, 42, 12, WS_GROUP
    PUSHBUTTON "Cancel", IDCANCEL, 96, 77, 42, 12
END

winmain.c :

 
Sélectionnez
#include <windows.h>

#include "resource.h"

#define DB_OK 1

#define FIN 1
#define MOYEN 2
#define LARGE 8

#define ID_CARRE 0
#define ID_CERCLE 1
#define ID_TRIANGLE 2

UINT Forme;
UINT Trait;

HINSTANCE hinst;

LRESULT CALLBACK MainWndProc(HWND, UINT, WPARAM, LPARAM);
BOOL APIENTRY Dialog1Proc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hPrevInstance,
                                                LPSTR lpCmdLine, int nCmdShow)
{
    HWND hwnd;
    MSG msg;
    WNDCLASS wc;

    hinst = hinstance;

    wc.style = 0;
    wc.lpfnWndProc = MainWndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hinstance;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(1 + COLOR_BTNFACE);
    wc.lpszMenuName =  "LEMENU";
    wc.lpszClassName = "MaWinClass";

    if(!RegisterClass(&wc)) return FALSE;

    hwnd = CreateWindow("MaWinClass", "Check Box", WS_OVERLAPPED | WS_SYSMENU,
                                        CW_USEDEFAULT, CW_USEDEFAULT, 400, 260,
                                                   NULL, NULL, hinstance, NULL);
    if (!hwnd) return FALSE;

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
}

/******************************************************************************/

LRESULT CALLBACK MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
        case WM_CREATE:
            Forme = ID_CARRE;
            Trait = FIN;
            return 0;

        case WM_COMMAND :
            if(LOWORD(wParam) == IDM_QUIT) PostMessage(hwnd, WM_CLOSE,0,0);
            if(LOWORD(wParam) == IDM_PROP)
              {
                if(DialogBox(hinst, "DIALOG1" , hwnd, (DLGPROC)Dialog1Proc)
                                                                      == DB_OK)
                                                 InvalidateRect(hwnd,NULL,TRUE);
              }
            return 0;

        case WM_PAINT :
            {
              PAINTSTRUCT ps;
              HDC hdc ;
              HPEN hpen, hpOld;

              POINT ptTriangle[3];
              ptTriangle[0].x = 20;
              ptTriangle[0].y = 20;
              ptTriangle[1].x = 20;
              ptTriangle[1].y = 170;
              ptTriangle[2].x = 170;
              ptTriangle[2].y = 95;

              hdc = BeginPaint(hwnd, &ps);

              hpen = CreatePen(PS_SOLID, Trait, 0);
              hpOld = SelectObject(hdc,hpen);

              if(Forme == ID_CARRE) Rectangle(hdc, 20, 20, 170, 170);

              if(Forme == ID_CERCLE) Ellipse(hdc, 20, 20, 170, 170);

              if(Forme == ID_TRIANGLE) Polygon(hdc, ptTriangle, 3);

              SelectObject(hdc,hpOld);
              DeleteObject(hpen);

              EndPaint(hwnd, &ps);
              return 0;
            }

        case WM_DESTROY :
            PostQuitMessage(0);
            return 0;

        default :
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
}

/******************************************************************************/

BOOL APIENTRY Dialog1Proc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
    switch (uMsg)
    {
      case WM_INITDIALOG:
         {
          SendDlgItemMessage(hDlg, ID_CB1, CB_ADDSTRING, 0, (LONG)"Carré");
          SendDlgItemMessage(hDlg, ID_CB1, CB_ADDSTRING, 0, (LONG)"Cercle");
          SendDlgItemMessage(hDlg, ID_CB1, CB_ADDSTRING, 0, (LONG)"Triangle");
          SendDlgItemMessage(hDlg, ID_CB1, CB_SETCURSEL, Forme, 0);

          if(Trait == FIN  ) CheckDlgButton(hDlg, ID_RB1, BST_CHECKED);
          if(Trait == MOYEN) CheckDlgButton(hDlg, ID_RB2, BST_CHECKED);
          if(Trait == LARGE) CheckDlgButton(hDlg, ID_RB3, BST_CHECKED);

          return TRUE;
         }

      case WM_COMMAND :
         if (LOWORD(wParam) == IDOK)
                {
                   if(IsDlgButtonChecked(hDlg, ID_RB1) == BST_CHECKED)
                                                                    Trait = FIN;
                   if(IsDlgButtonChecked(hDlg, ID_RB2) == BST_CHECKED)
                                                                  Trait = MOYEN;
                   if(IsDlgButtonChecked(hDlg, ID_RB3) == BST_CHECKED)
                                                                  Trait = LARGE;

                   Forme = SendDlgItemMessage(hDlg, ID_CB1, CB_GETCURSEL, 0, 0);

                   EndDialog(hDlg,DB_OK);
                   return TRUE;
                }

         if (LOWORD(wParam) == IDCANCEL)
                {
                   EndDialog(hDlg,0);
                   return TRUE;
                }

      default :
         return FALSE;
    }
}

La liste déroulante peut traiter de nombreux messages qui lui sont spécifiques. Je vous invite à consulter l'aide sur l'API Win32.
J'ai testé les compilations avec C++ Builder et DevC++.

À vos PC.

CGi

Sommaire

Vous avez aimé ce tutoriel ? Alors partagez-le en cliquant sur les boutons suivants : Viadeo Twitter Facebook Share on Google+   

Les sources présentées sur cette page sont libres de droits et vous pouvez les utiliser à votre convenance. Par contre, la page de présentation constitue une œuvre intellectuelle protégée par les droits d'auteur. Copyright © 2013 CGi. Aucune reproduction, même partielle, ne peut être faite de ce site ni de l'ensemble de son contenu : textes, documents, images, etc. sans l'autorisation expresse de l'auteur. Sinon vous encourez selon la loi jusqu'à trois ans de prison et jusqu'à 300 000 € de dommages et intérêts.