我正在尝试使用 mfc 在win32控制台窗口项目上创建一个简单的对话框,其中只有 ok 和取消按钮。我使用资源编辑器和必要的类创建了对话框模板。以下代码说明了项目
/*dialog.h - dialog class inherited from Cdialog*/
#pragma once
#include "resource.h"
#include "afxwin.h"
class dialog : public CDialog
{
DECLARE_DYNAMIC(dialog)
public:
dialog(CWnd* pParent = NULL); // standard constructor
virtual ~dialog();
// Dialog Data
enum { IDD = IDD_DIALOG1 };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP();
public:
BOOL OnInitDialog();
void OnOK();
void OnCancel();
void PostNcDestroy();
};
/* dialog.cpp : implementation file */
#include "stdafx.h"
#include "dialog.h"
#include "afxdialogex.h"
IMPLEMENT_DYNAMIC(dialog, CDialog)
dialog::dialog(CWnd* pParent /*=NULL*/)
: CDialog(dialog::IDD, pParent)
{}
dialog::~dialog()
{
DestroyWindow();
}
void dialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(dialog, CDialog)
END_MESSAGE_MAP()
// dialog message handlers
BOOL dialog::OnInitDialog()
{
CDialog::OnInitDialog();
return(TRUE);
}
void dialog::OnOK()
{
if (UpdateData(true))
DestroyWindow();
}
void dialog::OnCancel()
{
DestroyWindow();
}
void dialog::PostNcDestroy()
{
CDialog::PostNcDestroy();
delete this;
}
/*dialogbox.cpp : Defines the entry point for the console application.*/
#include "stdafx.h"
#include <iostream>
#include <afxwin.h>
#include <assert.h>
#include "dialog.h"
#include <thread>
DWORD WINAPI ModelessThreadFunc(LPVOID);
int _tmain(int argc, _TCHAR* argv[])
{
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), SW_SHOW))
{
std::cout<<"Fatal Error: MFC initialization failed\n";
}
else
{
CreateThread(NULL, 0, ModelessThreadFunc, NULL, 0, NULL);
HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, L"CloseModelessDialog");
while(WaitForSingleObject(hEvent, 0))
{
}
CloseHandle(hEvent);
}
return 0;
}
DWORD WINAPI ModelessThreadFunc(LPVOID)
{
dialog *dial = new dialog;
assert(dial->Create(dialog::IDD));
dial->ShowWindow(SW_SHOWNORMAL);
HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, L"CloseModelessDialog");
MSG msg;
while(WaitForSingleObject(hEvent, 0) != WAIT_OBJECT_0)
{
while(::GetMessage(&msg, NULL, 0,0) != 0)
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
}
CloseHandle(hEvent);
return 0;
}
对话框运行正常。但按下确定或关闭后,对话框关闭,我的主程序没有结束。我认为事件并未结束。任何人都可以澄清吗?
答案 0 :(得分:0)
如果您有自己的UI线程,可以使用Dialog的地址设置m_pMainWnd指针。 你不需要自己的消息Loop。
PS:将CreateThread与MFC一起使用,CRT可能导致内存泄漏。始终使用CRT线程例程或AfxBeginThread。