win32删除消息循环对象

时间:2016-08-18 13:01:14

标签: c++ winapi design-patterns

我决定不在消息循环中使用switch-case。相反,我编写了抽象消息类(MessageHandler),以便每个消息继承该类并实现该做什么。

问题在于找到我应该在哪里制作每个消息对象并将其删除是不明确的。所有消息都应该保留,直到程序结束 但根据我的理解,我可以删除此消息对象的唯一地方是关闭消息本身,这是无法完成的。

我应该改变整个设计还是有办法做到这一点?

这是消息类。 (对不起,我无法总结代码以减少它们)

class MessageHandler
{
private:
    UINT message;
public:
    static vector<MessageHandler*> msgs;
public:
    inline MessageHandler(UINT _message){ setMessage(_message); registerMsg(this); }
    virtual ~MessageHandler() = default;
    virtual void handleMessage() = 0;

    inline void registerMsg(MessageHandler *handlerObj) { msgs.push_back(handlerObj); }
    inline UINT getMessage(){ return message; }
    inline void setMessage(UINT _message){ message = _message; }
};

class WMQUITmsg : public MessageHandler
{
public:
    inline WMQUITmsg() : MessageHandler(WM_QUIT) {}
    ~WMQUITmsg() = default;
    void handleMessage();
};

class WMCLOSEmsg : public MessageHandler
{
public:
    inline WMCLOSEmsg() : MessageHandler(WM_CLOSE) {}
    ~WMCLOSEmsg() = default;
    void handleMessage();
};

class WMDESTROYmsg : public MessageHandler
{
public:
    inline WMDESTROYmsg() : MessageHandler(WM_DESTROY) {}
    ~WMDESTROYmsg() = default;
    void handleMessage();
};

这就是我使用它们的方式

class EventHandler
{
public:
    bool runMessageLoop(UINT _message);
};
bool EventHandler::runMessageLoop(UINT _message)
{
    bool foundMsg = false;
    for(auto& it : MessageHandler::msgs)
    {
        if(it->getMessage() == _message)
        {
            foundMsg = true;
            it->handleMessage();
        }
    }
    return foundMsg;
}

WinMain将调用此函数。

int ApplicationMain (HINSTANCE hInst,
            HINSTANCE hPrevInst,
            char *cmdParam,
            int cmdShow,
            const char *className)
{
    //싱글톤 객체 생성
    ApplicationManager* AppManager = ApplicationManager::getAppManger();

    WindowClass winClass(WindowProcedure, className, hInst);
    if(winClass.Register())
    {

        WindowMaker win(className, hInst);
        AppManager->setMessages();

        AppManager->setRunLoop();
    }       
    return 0;
}

setMessages给这个

WMQUITmsg *a = new WMQUITmsg();
WMCLOSEmsg *b = new WMCLOSEmsg();
WMDESTROYmsg *c = new WMDESTROYmsg();

我相信这会导致内存泄漏,因为永远不能删除setMessages内的消息对象,直到程序终止为止。

0 个答案:

没有答案