在动态库中创建Win32窗口

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);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值