Home > Blockchain >  How to create multiple instances of the same Dialog Procedure in win32?
How to create multiple instances of the same Dialog Procedure in win32?

Time:12-02

Within a modeless DialogBoxProcedure(), I implemented two main functions:

  1. Constant movement along the X and Y axis using SetWindowPos(), each movement activated by a timer. (Essentially making the Dialog Box bounce around the screen). I did this by using static int to set the variables, and adjust them accordingly upon receiving a new timer message.

  2. Recursively Creating a new DialogBox by calling CreateDialog() whenever the original Dialog Box receives the appropriate message to do so.

I wanted the new recursively created dialog box to call on its own DialogBoxProcedure with its own set of static variables so it could move independently, but what ended up happening was the new DialogBox was stacked exactly on top of the previous dialog box,probably because of the usage of static variables in the DialogProcedure. Is there a way to fix this?

CodePudding user response:

You can't create multiple instances of the same dialog procedure. You can use the same dialog procedure more than once and make sure it knows which dialog it's talking about.

Store the variables in some kind of structure and make two instances of that, for example using malloc or just two different global or static variables.

Then:

  • Instead of CreateDialog use CreateDialogParam and give it a pointer:

      // instead of
      hWndDialog = CreateDialog(     hInstance, IDD_MY_DIALOG, hWndParent, MyDialogProc);
      // use:
      hWndDialog = CreateDialogParam(hInstance, IDD_MY_DIALOG, hWndParent, MyDialogProc, pMyDialogStruct1);
      //                       ^^^^^                                                     ^^^^^^^^^^^^^^^^
    
  • When your dialog proc gets a WM_INITDIALOG message, that pointer is in lParam. You can then transfer it to the HWND by using SetWindowLongPtr(DWLP_USER):

      SetWindowLongPtr(hWnd, DWLP_USER, (LONG_PTR)lParam);
    
  • Now the struct pointer is stored in the HWND and you can get it back at any time:

      MyDialogStruct* dlgStruct = (MyDialogStruct*)GetWindowLongPtr(hWnd, DWLP_USER);
    
  • Related