Search code examples
c++classwinapiprogram-entry-point

How do I create multiple windows in different classes than the main function in C++ with Win32


How do I create multiple windows in different classes than the WinMain function in C++ with Win32?

What I am trying to do:

My Source Files:

  • FileThatContainsMainFunction.cpp
  • Window1.cpp
  • Window2.cpp

In the Main Function I would like to make two objects (one for Window1 and one or Window2) that create Win32 Windows in their constuctors. eg:

Window1 w1;
Window2 w2;

Note: This question is directed towards C++ classes, not Win32 Classes.


Solution

  • It works pretty much the way you described in your question:

    Window1.h

    #ifndef Window1H
    
    #include <windows.h>
    
    class Window1
    {
    private:
        HWND hWnd;
    public:
        Window1();
        ~Window1();
    };
    
    #endif
    

    Window1.cpp

    #include "Window1.h"
    
    Window1::Window1()
    {
        // register and create window as needed
        hWnd = CreateWindowEx(...);
    }
    
    Window1::~Window1()
    {
        DestroyWindow(hWnd);
    }
    

    Window2.h

    #ifndef Window2H
    
    #include <windows.h>
    
    class Window2
    {
    private:
        HWND hWnd;
    public:
        Window2();
        ~Window2();
    };
    
    #endif
    

    Window2.cpp

    #include "Window2.h"
    
    Window2::Window2()
    {
        // register and create window as needed
        hWnd = CreateWindowEx(...);
    }
    
    Window2::~Window2()
    {
        DestroyWindow(hWnd);
    }
    

    FileThatContainsMainFunction.cpp

    #include "Window1.h"
    #include "Window2.h"
    
    int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
    {
        Window1 w1;
        Window2 w2;
        //...
        return 0;
    }