用CDialogImpl创建窗口

  • Post author:
  • Post category:其他


1、使用Atl创建窗口使用模板对象CDialogImpl<CTestDialog>,CTestDialog派生该模板对象窗口后,即可非模态对话框,又可创建模态对话框;

2、创建非模态对话框的方式为:Create(NULL) 和 ShowWindow(SW_SHOW),关闭则用DestroyWindow();

3、创建模态对话框的方式为:DoModal(NULL),关闭则用EndDialog(0);

4、在调用DestroyWindow和EndDialog之后,系统会释放窗口资源,等释放为窗口资源后,发送WM_DESTROY消息;

5、在处理WM_DESTROY消息时,利用PostQuitMessage(0),退出消息循环;

TestDialog.h

#pragma once

class CTestDialog : public CDialogImpl<CTestDialog>
{
public:
	enum { IDD = IDD_DIALOG1};

public:
	CTestDialog(void);
	~CTestDialog(void);

	BEGIN_MSG_MAP(CTestDialog)
		MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
		MESSAGE_HANDLER(WM_CLOSE, OnClose)
		MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
		COMMAND_ID_HANDLER(IDOK, OnOK)
		COMMAND_ID_HANDLER(IDCANCEL, OnCancel)
	END_MSG_MAP()

public:
	LRESULT OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
	LRESULT OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
	LRESULT OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
	LRESULT OnOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);
	LRESULT OnCancel(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);
};

TestDialog.cpp

#include "stdafx.h"
#include "TestDialog.h"


CTestDialog::CTestDialog(void)
{
}

CTestDialog::~CTestDialog(void)
{
}

LRESULT CTestDialog::OnInitDialog( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
	bHandled = TRUE;
	return TRUE;
}

LRESULT CTestDialog::OnClose( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
	MessageBox(L"OnClose", L"CTestDialog", 0);
	DestroyWindow();// send message to OnDestroy; Non Modal Dialog
	bHandled = TRUE;
	return TRUE;
}

LRESULT CTestDialog::OnDestroy( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
	MessageBox(L"OnDestroy", L"CTestDialog", 0);
	PostQuitMessage(0);
	bHandled = TRUE;
	return TRUE;
}

LRESULT CTestDialog::OnOK( WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled )
{
	bHandled = TRUE;
	EndDialog(0); // send message to OnDestroy; Modal Dialog
	return 0;
}

LRESULT CTestDialog::OnCancel( WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled )
{
	bHandled = TRUE;
	EndDialog(0);
	return 0;
}

main.cpp

#include "stdafx.h"
#include "TestDialog.h"

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
	// 创建模态窗口
	CTestDialog testDialog;
	testDialog.DoModal(NULL);

// 创建非模态窗口
//CTestDialog testDialog;
	//testDialog.Create(NULL);
	//testDialog.ShowWindow(SW_SHOW);

	MSG msg;
	while(GetMessage(&msg, NULL, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

    return 0;
}



版权声明:本文为gwzz1228原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。