向量和HWND零内存错误c ++

时间:2015-01-09 16:36:58

标签: c++ windows winapi vector hwnd

我想创建多个窗口..因为我不是一遍又一遍地写它们,我决定使用vector来保存所有 HWND 的列表,并在程序进行时更新它们。但它似乎并不像按预期工作..它给了我一个访问冲突错误。

我尝试初始化vector.But似乎什么都没有用

WindoManager.h

  #include<windowsx.h>
#include<Windows.h>
#include<vector>
#include<list>
#include<iostream>
using namespace std;


class WindowManager{

    // Constructor
    WindowManager();

    // Destructor
    ~WindowManager();

private:
    vector<HWND> wnds;
    HWND hwnd;

public:
    void CreateNewWindow(HINSTANCE hinst,WNDCLASSEX * ex,HWND * Parent,HWND * ReturnWind,int Width,int Height,int X,int Y);
    void ShowWindows(int);
    int HandleMseeages();

};

WindowManager.cpp

#include"WindowManager.h"

WindowManager::WindowManager()
{


}

void WindowManager::CreateNewWindow(HINSTANCE hinst,WNDCLASSEX * ex,HWND * Parent,HWND * ReturnWind,int Width,int Height,int X,int Y)
{
    if(Parent == NULL)
    {
      hwnd = CreateWindowEx(NULL,ex->lpszClassName,ex->lpszMenuName,WS_OVERLAPPEDWINDOW,X,Y,Width,Height,NULL,NULL,hinst,NULL);
        wnds.push_back(hwnd);
        *ReturnWind = hwnd;
    }
}

void WindowManager::ShowWindows(int show)
{
    for(vector<HWND>::iterator it = wnds.begin();it != wnds.end() ; ++it)
    {
        ShowWindow(*it,show);
    }
}


int WindowManager::HandleMseeages()
{
    MSG msg;

 for(int i=0;i< wnds.size();++i)
    {
        if(PeekMessage(&msg,wnds[i],0,0,PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);

            if(msg.message == WM_QUIT)
                return 0;
        }
    }

 return 1;
}

该函数从source.cpp调用

....//Removed unwanted code

WindowManager * WndManager = {0};

    WndManager->CreateNewWindow(hinst,&classex,NULL,&hwnd,500,500,0,0);
    WndManager->ShowWindows(cmdshow);

我不知道什么是错的。请帮帮我

感谢

2 个答案:

答案 0 :(得分:0)

试试这个:

WindowManager WndManager{};

WndManager.CreateNewWindow(hinst,&classex,NULL,&hwnd,500,500,0,0);
WndManager.ShowWindows(cmdshow);

答案 1 :(得分:0)

问题似乎在于这一行:

WindowManager * WndManager = {0};

您正在声明指针而不分配对象并调用它的构造函数。

将对象分配为:

WindowManager * WndManager = new WindowManager;

或者只是简单地在堆栈中定义它并使用正确的调用(如 Richard Hodges 所建议的那样):

WindowManager WndManager;

WndManager.CreateNewWindow(hinst,&classex,NULL,&hwnd,500,500,0,0);
WndManager.ShowWindows(cmdshow);