3.不规则窗口

1.不规则窗口

  原理:用一个位图画刷绘制窗口背景,然后把想要透明的颜色设置为透明色,就可以使窗口变成任意形状。

 1 //窗口处理函数
 2 LRESULT CALLBACK BitmapWindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
 3 {
 4   static HDC s_hdcMem;
 5   static HBRUSH s_hBackBrush; 
 6   COLORREF clTransparent;//透明色  
 7   switch (message)
 8   {
 9   case WM_CREATE: 
10     SetWindowLong(hWnd, GWL_EXSTYLE, GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);//设置分层属性 
11     clTransparent = RGB(0, 0, 0);
12     //将黑色设置为完全透明,0表示完全透明 
13     SetLayeredWindowAttributes(hWnd, clTransparent, 0, LWA_COLORKEY);
14     return 0;
15   case WM_KEYDOWN:
16     //按下Esc键时退出
17     if (VK_ESCAPE == wParam)  
18     {
19       SendMessage(hWnd, WM_DESTROY, 0, 0);
20       return 0;
21     }
22     break;   
23   case WM_LBUTTONDOWN: 
24     //当鼠标左键点击时可以拖曳窗口
25     PostMessage(hWnd, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);
26     return 0;
27   case WM_DESTROY:
28     PostQuitMessage(0);
29     return 0;
30   }
31   return DefWindowProc(hWnd, message, wParam, lParam);
32 }
33 
34 //初始化为位图窗口(注册窗口类、创建窗口、显示窗口)
35 BOOL InitBitmapWindow(HINSTANCE hInstance, HBITMAP hBitmap, int nCmdShow)
36 {
37   //注册窗口类
38   WNDCLASS wndclass;
39   wndclass.cbClsExtra = 0;
40   wndclass.cbWndExtra = 0;
41   wndclass.hbrBackground = CreatePatternBrush(hBitmap);
42   wndclass.hCursor = NULL;
43   wndclass.hIcon = NULL;
44   wndclass.lpfnWndProc = BitmapWindowProc;
45   wndclass.lpszClassName = L"Hello";
46   wndclass.lpszMenuName = NULL;
47   wndclass.hInstance = hInstance;
48   wndclass.style = CS_HREDRAW | CS_VREDRAW;
49   if (!RegisterClass(&wndclass))
50   {
51     MessageBox(NULL, L"Program Need Windows NT", L"Error", MB_ICONERROR);
52     return FALSE;
53   }
54   BITMAP bmp;
55   GetObject(hBitmap, sizeof(bmp), &bmp);
56   //创建窗口
57   HWND hWnd = CreateWindowEx(WS_EX_TOPMOST, L"Hello", L"HelloKitty", WS_POPUP, CW_USEDEFAULT, CW_USEDEFAULT,
58                              bmp.bmWidth, bmp.bmHeight, NULL, NULL, hInstance, NULL);
59   if (NULL == hWnd)
60   {
61     return FALSE;
62   }
63   //显示窗口
64   ShowWindow(hWnd, nCmdShow);
65   UpdateWindow(hWnd);
66   return TRUE;
67 }
68 
69 int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
70 {
71   HBITMAP hBitmap = (HBITMAP)LoadImage(NULL, L"kitty.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
72   if (NULL == hBitmap)
73   {
74     MessageBox(NULL, L"加载位图失败", L"Error", MB_ICONERROR);
75     return -1;
76   }
77   if (!InitBitmapWindow(hInstance, hBitmap, nCmdShow))
78   {
79     return -1;
80   }    
81   MSG msg;
82   while (GetMessage(&msg, NULL, 0, 0))
83   {
84     TranslateMessage(&msg);
85     DispatchMessage(&msg);
86   }
87   DeleteObject(hBitmap);
88   return 0;
89 }

  运行效果:

  

posted @ 2016-09-19 13:53  甩锅侠  阅读(204)  评论(0编辑  收藏  举报