Dave's Brain

Browse - programming tips - dialog box param

Date: 2004Aug24
OS: Windows

Q. Is there a way to avoid global variables with win32 dialogs?

A. Use DialogBoxParam() and Set/GetDialogData() like this:

typedef enum {R_ NOT_STARTED, R_OK, R_CANCEL } MY_RESULT;

struct Record
{
   int     stuff1;
   int     stuff2;
   int     stuff3;
};

static BOOL __stdcall
MyDialogDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    WORD        id, code;

    switch (message)
    {
    case WM_INITDIALOG:
       {
           Record *pRecord = (Record *) lParam;

           SetDialogData(hDlg, pRecord);
           Load(hDlg, pRecord);
       }
       return TRUE;

    case WM_COMMAND:
       id = LOWORD(wParam);
       code = HIWORD(wParam);

       switch(id)
       {
       case IDOK: 
          {
             Record *pRecord = (Record *) GetDialogData(hDlg);

             Save(hDlg, pRecord);
             EndDialog(hDlg, R_OK);
          }
          break;

       case IDCANCEL:
          EndDialog(hDlg, R_CANCEL);
          break;
       }
       break; // end of WM_COMMAND
    }

    return FALSE;
}

MY_RESULT MyDialog(const HWND hDlg, Record *record)
{
   return (MY_RESULT) DialogBoxParam(ghInstance, MAKEINTRESOURCE(IDD_MY_DIALOG), hDlg, (DLGPROC) MyDialogDlgProc, (LPARAM)record);
}

Add a comment

Sign in to add a comment
Copyright © 2008, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.