|
自定义一个windows窗口类 new时显示 delete时隐藏,可以方便的在自己的项目中使用原创文章拒绝转载
使用方法如下:
- #include "SpecialWnd.h"
- SpecialWnd * swnd;
- void CTestDlg::OnBnClickedButton8()
- {
- if (swnd == NULL)
- {
- swnd = new SpecialWnd(AfxGetApp()->m_hInstance,//模块句柄
- this->GetSafeHwnd(),//父窗口句柄,可以是其它进程的
- 0, 0, 100, 100);//x,y,width,height
- }
- }
- void CTestDlg::OnBnClickedButton9()
- {
- if (swnd)
- {
- delete swnd;
- swnd = NULL;
- }
- }
复制代码
头文件如下:
- #pragma once
- #include <Windows.h>
- #include <map>
- class SpecialWnd
- {
- public:
- SpecialWnd(HINSTANCE hInstance, HWND hWndParent,int x,int y,int width, int height);
- ~SpecialWnd();
- static std::map<HWND, SpecialWnd*> windowMap;//句柄和对象的对应关系
- private:
- HWND hWnd;
-
- };
复制代码 cpp文件如下:
- #include "stdafx.h"
- #include "SpecialWnd.h"
- std::map<HWND, SpecialWnd*> SpecialWnd::windowMap;
- LRESULT CALLBACK WndProc(HWND hWnd,
- UINT msg,
- WPARAM wParam,
- LPARAM lParam)
- {
- SpecialWnd *pThisWnd = NULL;//用于在对应的对象内处理窗口消息
- if (SpecialWnd::windowMap.find(hWnd) != SpecialWnd::windowMap.end())
- {
- pThisWnd = SpecialWnd::windowMap[hWnd];
- }
- switch (msg)
- {
- case WM_LBUTTONDOWN:
- {
- if (pThisWnd != NULL)
- {
- }
- }
- break;
- case WM_RBUTTONDOWN:
- {
- if (pThisWnd != NULL)
- {
- }
- }
- break;
- case WM_DESTROY:
- break;
- default:
- return ::DefWindowProc(hWnd, msg, wParam, lParam);
- }
- return 0;
- }
- SpecialWnd::SpecialWnd(HINSTANCE hInstance, HWND hWndParent, int x, int y, int width, int height)
- {
- TCHAR lpszClassName[] = TEXT("SpecialWnd");
- WNDCLASS wc;
- wc.style = CS_HREDRAW | CS_VREDRAW;
- wc.lpfnWndProc = WndProc;
- wc.cbClsExtra = 0;
- wc.cbWndExtra = 0;
- wc.hInstance = hInstance;
- wc.hIcon = ::LoadIcon(NULL, IDI_APPLICATION);
- wc.hCursor = ::LoadCursor(NULL, IDC_ARROW);
- wc.hbrBackground = (HBRUSH)::GetStockObject(WHITE_BRUSH);
- wc.lpszMenuName = NULL;
- wc.lpszClassName = lpszClassName;
- RegisterClass(&wc);
- hWnd = CreateWindow(lpszClassName,
- TEXT("Windows"),
- WS_POPUP | WS_DLGFRAME | WS_VISIBLE,//不带标题栏
- x, y, width, height,
- hWndParent,
- NULL,
- hInstance,
- NULL);
- ::ShowWindow(hWnd, SW_SHOWNORMAL);
- ::UpdateWindow(hWnd);
- // 实现透明必须设置WS_EX_LAYERED标志
- LONG nRet = ::GetWindowLong(hWnd, GWL_EXSTYLE);
- nRet = nRet | WS_EX_LAYERED;
- ::SetWindowLong(hWnd, GWL_EXSTYLE, nRet);
- ::SetLayeredWindowAttributes(hWnd, 0, 123, LWA_ALPHA); // 设置半透明
- RECT rctA;
- ::GetWindowRect((HWND)(hWndParent), &rctA);
- ::MoveWindow(hWnd, rctA.left, rctA.top,
- (rctA.right - rctA.left)/2, (rctA.bottom - rctA.top)/2, TRUE);//覆盖父窗口的一半
- SpecialWnd::windowMap[hWnd] = this;
- }
- SpecialWnd::~SpecialWnd()
- {
-
- if (::IsWindow(hWnd))
- {
- if (SpecialWnd::windowMap.find(hWnd) != SpecialWnd::windowMap.end())
- {
- SpecialWnd::windowMap.erase(hWnd);
- }
- ::ShowWindow(hWnd, SW_HIDE);
- ::DestroyWindow(hWnd);
- hWnd = NULL;
- }
- //::CloseHandle(hWnd);
- }
复制代码 优点就是控制简单,new显示,delete隐藏。创建参数少。内部的样式可以自己调整。
|
|