extern HINSTANCE g_hInstance; // 动态库句柄
struct SimepleWnd
{
HWND hWnd;
int nX;
int nY;
int nWidth;
int nHeight;
HANDLE hEvent;
HANDLE hThread;
CHAR szWndName[256];
UINT nSize;
SimepleWnd(CHAR *szWndName,int x, int y, int nWidth, int nHeight)
{
nX = x;
nY = y;
this->nWidth = nWidth;
this->nHeight = nHeight;
if (szWndName)
strcpy_s(this->szWndName, 256, szWndName);
hEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr);
nSize = sizeof(SimepleWnd);
}
~SimepleWnd()
{
if (hEvent)
CloseHandle(hEvent);
}
// 为窗口启动独立的消息循环线程
BOOL StartMessageLoop()
{
hThread = (HANDLE)_beginthreadex(nullptr, 0, ThreadMessageLoop, this, nullptr, 0);
if (hThread)
{
CloseHandle(hThread);
return TRUE;
}
else
{
return FALSE;
}
}
void WaitForMessageLoop()
{
while (WaitForSingleObject(this->hEvent, 0) == WAIT_TIMEOUT)
{
Sleep(25);
}
}
BOOL CreateSimpleWindow()
{
hWnd = CreateDialog(g_hInstance, MAKEINTRESOURCE(IDD_DIALOG), nullptr, DialogProc);
if (hWnd)
{
MoveWindow(hWnd, nX, nY, nWidth, nHeight, FALSE);
SetWindowText(hWnd, szWndName);
ShowWindow(hWnd, SW_NORMAL);
return TRUE;
}
else
return FALSE;
}
// 窗口回调函数
static INT_PTR CALLBACK DialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_CLOSE:
{
PostMessage(hDlg, WM_DESTROY, 0, 0);
break;
}
case WM_DESTROY:
{
DestroyWindow(hDlg);
break;
}
}
return (INT_PTR)FALSE;
}
static UINT ThreadMessageLoop(void *p)
{
SimepleWnd *pThis = (SimepleWnd*)p;
if (!pThis->CreateSimpleWindow())
return 0;
SetEvent(pThis->hEvent);
MSG msg;
while (::GetMessage(&msg, pThis->hWnd, 0, 0))
{
if (IsWindow(pThis->hWnd))
{
if (msg.message == WM_DESTROY)
break;
}
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
delete pThis;
return 0;
}
};
// 创建窗口的对外函数接口
HWND CreateSimpleWindow(CHAR *szWndName,int x,int y,int nWidth, int nHeight)
{
SimepleWnd *pWnd = new SimepleWnd(szWndName, x, y, nWidth, nHeight);
if (pWnd)
{
if (pWnd->StartMessageLoop())
pWnd->WaitForMessageLoop();
return pWnd->hWnd;
}
else
return nullptr;
}
// 销毁窗口的对外接口
void DestroySimpleWindow(HWND hWnd)
{
if (!hWnd || !IsWindow(hWnd))
return;
SimepleWnd *pWnd = CONTAINING_RECORD(&hWnd, SimepleWnd, hWnd);
if (pWnd->nSize == sizeof(SimepleWnd))
SendMessage((HWND)pWnd->hWnd, WM_CLOSE, 0, 0);
}