酷代码 AI
菜单

c++windows api黑色背景显示随机一张纸牌,用绘图

以下是一个使用Windows API在黑色上随机显示一张纸牌的C++示例代码。我们将使用Windows的绘图功能来绘制纸牌的形状和花色。 ```cpp #include <windows.h> #include <iostream> #include <cstdlib> #include <ctime> // 定义纸牌的花色和点数 const char* suits[] = { "♠", "♥", "♣", "♦" }; const char* ranks[] = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" }; // 窗口过程函数 LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); // 设置黑色 HBRUSH hBrush = CreateSolidBrush(RGB(0, 0, 0)); FillRect(hdc, &ps.rcPaint, hBrush); DeleteObject(hBrush); // 随机选择一张纸牌 srand(static_cast<unsigned int>(time(0))); int suitIndex = rand() % 4; int rankIndex = rand() % 13; // 设置文本颜色为白色 SetTextColor(hdc, RGB(255, 255, 255)); SetBkMode(hdc, TRANSPARENT); // 绘制纸牌的边框 RECT cardRect; cardRect.left = 100; cardRect.top = 100; cardRect.right = 200; cardRect.bottom = 300; HPEN hPen = CreatePen(PS_SOLID, 2, RGB(255, 255, 255)); HBRUSH hOldBrush = (HBRUSH)SelectObject(hdc, GetStockObject(NULL_BRUSH)); HPEN hOldPen = (HPEN)SelectObject(hdc, hPen); Rectangle(hdc, cardRect.left, cardRect.top, cardRect.right, cardRect.bottom); SelectObject(hdc, hOldPen); SelectObject(hdc, hOldBrush); DeleteObject(hPen); // 绘制纸牌的点数和花色 std::string cardText = std::string(ranks[rankIndex]) + std::string(suits[suitIndex]); int textX = cardRect.left + (cardRect.right - cardRect.left - GetTextExtentPoint32(hdc, cardText.c_str(), static_cast<int>(cardText.length()), NULL).cx) / 2; int textY = cardRect.top + (cardRect.bottom - cardRect.top - GetTextExtentPoint32(hdc, cardText.c_str(), static_cast<int>(cardText.length()), NULL).cy) / 2; TextOut(hdc, textX, textY, cardText.c_str(), static_cast<int>(cardText.length())); EndPaint(hwnd, &ps); break; } case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; } // 主函数 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { // 注册窗口类 WNDCLASS wc = {}; wc.lpfnWndProc = WndProc; wc.hInstance = hInstance; wc.lpszClassName = L"CardWindowClass"; RegisterClass(&wc); // 创建窗口 HWND hwnd = CreateWindow(wc.lpszClassName, L"Random Card", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 800, 600, NULL, NULL, hInstance, NULL); // 显示窗口 ShowWindow(hwnd, iCmdShow); UpdateWindow(hwnd); // 消息循环 MSG msg = {}; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return static_cast<int>(msg.wParam); } ``` 代码说明: 1. 定义纸牌信息:使用两个数组 `suits` 和 `ranks` 分别存储纸牌的花色和点数。 2. 窗口过程函数 `WndProc`:处理 `WM_PAINT` 消息,在该消息中设置黑色,随机选择一张纸牌,并绘制纸牌的边框和内容。 3. 主函数 `WinMain`:注册窗口类,创建窗口,显示窗口,并进入消息循环。 编译和运行: 将上述代码保存为 `.cpp` 文件,使用支持Windows API的编译器(如Visual Studio)进行编译和运行。运行程序后,会弹出一个窗口,在黑色上显示一张随机的纸牌。 [2026-01-24 09:40:18 | AI问答 | 1201点数解答]

服务商
相关提问
发财导航,免费问AI
实用工具查看更多