gdi 使用png做异形窗口 ,完整demo
时间: 2023-07-20 19:30:56 浏览: 56
以下是一个使用 GDI 和 PNG 图像创建异形窗口的完整 Demo:
```c++
#include <Windows.h>
#include <gdiplus.h>
#pragma comment(lib, "Gdiplus.lib")
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
WNDCLASSEX wc = { 0 };
wc.cbSize = sizeof(WNDCLASSEX);
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszClassName = TEXT("MyWindowClass");
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
RegisterClassEx(&wc);
HWND hwnd = CreateWindowEx(WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
TEXT("MyWindowClass"), TEXT("My Window"), WS_POPUP,
100, 100, 400, 300, NULL, NULL, hInstance, NULL);
// 加载 PNG 图像
Gdiplus::Bitmap* bitmap = Gdiplus::Bitmap::FromFile(L"path/to/image.png");
Gdiplus::Rect rect(0, 0, bitmap->GetWidth(), bitmap->GetHeight());
Gdiplus::BitmapData bitmapData;
bitmap->LockBits(&rect, Gdiplus::ImageLockModeRead, PixelFormat32bppARGB, &bitmapData);
// 创建位图
HDC hdc = GetDC(hwnd);
HDC memdc = CreateCompatibleDC(hdc);
HBITMAP hbitmap = CreateBitmap(bitmap->GetWidth(), bitmap->GetHeight(), 1, 32, bitmapData.Scan0);
// 设置窗口透明度和形状
SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 0, LWA_COLORKEY);
HRGN region = CreateRoundRectRgn(0, 0, bitmap->GetWidth(), bitmap->GetHeight(), 20, 20);
SetWindowRgn(hwnd, region, TRUE);
// 绘制位图到窗口
SelectObject(memdc, hbitmap);
BITMAP bm;
GetObject(hbitmap, sizeof(BITMAP), &bm);
BitBlt(hdc, 0, 0, bm.bmWidth, bm.bmHeight, memdc, 0, 0, SRCCOPY);
// 释放资源
DeleteObject(hbitmap);
DeleteDC(memdc);
ReleaseDC(hwnd, hdc);
bitmap->UnlockBits(&bitmapData);
delete bitmap;
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
Gdiplus::GdiplusShutdown(gdiplusToken);
return (int)msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
```
这个 Demo 首先使用 GDI+ 库加载 PNG 图像,然后创建位图并将其绘制到窗口上。其中,使用 `SetLayeredWindowAttributes` 函数设置窗口透明度和颜色键,使用 `CreateRoundRectRgn` 函数创建圆角矩形区域来设置窗口形状。最后,通过消息循环等待窗口被销毁。