c++ 根据图片生成异形窗口并在生成的窗口上画图
时间: 2023-12-23 22:03:02 浏览: 111
创建异形窗体
要生成异形窗口并在窗口上绘制图片,可以使用以下步骤:
1. 加载图片,可以使用GDI+库或其他图片处理库。
2. 创建一个透明的窗口,可以使用Windows API的CreateWindowEx函数,并设置窗口的样式为WS_EX_LAYERED。
3. 使用Windows API的UpdateLayeredWindow函数将图片绘制到窗口上。
下面是一个简单的示例代码,可以根据名为"image.bmp"的图片生成异形窗口并在窗口上绘制图片:
```
#include <Windows.h>
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// 加载图片
Gdiplus::Bitmap* bmp = Gdiplus::Bitmap::FromFile(L"image.bmp");
if (bmp != NULL)
{
// 绘制图片
Gdiplus::Graphics graphics(hdc);
graphics.DrawImage(bmp, 0, 0);
delete bmp;
}
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// 加载图片
Gdiplus::Bitmap* bmp = Gdiplus::Bitmap::FromFile(L"image.bmp");
if (bmp == NULL)
return 0;
// 获取图片的大小
int width = bmp->GetWidth();
int height = bmp->GetHeight();
// 创建透明窗口
HWND hWnd = CreateWindowEx(WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW, L"MyWindowClass", L"Window Title", WS_POPUP,
0, 0, width, height, NULL, NULL, hInstance, NULL);
if (hWnd == NULL)
return 0;
// 设置窗口的透明度
SetLayeredWindowAttributes(hWnd, RGB(0, 0, 0), 0, LWA_COLORKEY);
// 使用UpdateLayeredWindow函数将图片绘制到窗口上
HDC hdcScreen = GetDC(NULL);
HDC hdcMem = CreateCompatibleDC(hdcScreen);
HBITMAP hBitmap = CreateBitmap(width, height, 1, 32, bmp->GetBits());
HBITMAP hOldBitmap = (HBITMAP)SelectObject(hdcMem, hBitmap);
POINT ptDst = { 0, 0 };
SIZE sz = { width, height };
POINT ptSrc = { 0, 0 };
BLENDFUNCTION blend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
UpdateLayeredWindow(hWnd, hdcScreen, &ptDst, &sz, hdcMem, &ptSrc, 0, &blend, ULW_ALPHA);
SelectObject(hdcMem, hOldBitmap);
DeleteObject(hBitmap);
DeleteDC(hdcMem);
ReleaseDC(NULL, hdcScreen);
// 注册窗口类
WNDCLASS wc = { 0 };
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszClassName = L"MyWindowClass";
RegisterClass(&wc);
// 显示窗口
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
// 消息循环
MSG msg = { 0 };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
```
阅读全文