用C++写一个带窗口的进度条项目
时间: 2024-09-28 19:16:54 浏览: 68
在C++中创建一个简单的带窗口的进度条项目通常会涉及到Windows API或者一些跨平台的图形库,比如Qt或wxWidgets。这里我会给出一个基本的使用Windows API的例子,展示如何创建一个简单的GUI程序,其中包括一个进度条。
```cpp
#include <windows.h>
#include <iostream>
// 进度条结构体
struct ProgressBar {
HWND hWnd; // 窗口句柄
HINSTANCE hInstance; // 应用实例
int minValue, maxValue; // 进度条范围
int value; // 当前进度值
};
void DrawProgressBar(HWND hWnd, ProgressBar& progressBar) {
// 计算进度条尺寸
RECT rect;
GetClientRect(hWnd, &rect);
int width = rect.right - rect.left;
// 绘制进度条
HDC hdc = BeginPaint(hWnd, &PAINTSTRUCT);
HBRUSH brush = CreateSolidBrush(progressBar.value ? RGB(0, 255, 0) : RGB(255, 0, 0));
HPEN pen = CreatePen(PS_SOLID, 1, RGB(0, 0, 0));
// 创建矩形区域
MoveToEx(hdc, 0, height / 2, NULL);
LineTo(hdc, width, height / 2);
// 绘制进度部分
HGDIOBJ oldPen = SelectObject(hdc, pen);
DrawRect(hdc, rect.left, rect.top, rect.right * progressBar.value / (progressBar.maxValue - progressBar.minValue), rect.bottom);
// 绘制完成区域
SelectObject(hdc, brush);
FillRect(hdc, &rect, brush);
// 清理资源
DeleteObject(brush);
DeleteObject(pen);
SelectObject(hdc, oldPen);
EndPaint(hWnd, &PAINTSTRUCT);
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_CREATE:
// 初始化进度条
ProgressBar progressBar;
progressBar.hWnd = hWnd;
progressBar.hInstance = GetWindowLong(hWnd, GWL_HINSTANCE);
progressBar.minValue = 0;
progressBar.maxValue = 100;
progressBar.value = 0;
return DefWindowProc(hWnd, msg, wParam, lParam);
case WM_PAINT:
DrawProgressBar(hWnd, progressBar);
break;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
PostQuitMessage(0); // 结束应用
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
WNDCLASS wc = {0};
wc.lpfnWndProc = WndProc;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszClassName = "ProgressWindowClass";
if (!RegisterClass(&wc)) {
std::cerr << "Failed to register window class!" << std::endl;
return 0;
}
HWND hWnd = CreateWindowEx(NULL,
"ProgressWindowClass",
"Simple Progress Bar Example",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
400, 100,
NULL, NULL,
hInstance, NULL);
if (!hWnd) {
std::cerr << "Failed to create window!" << std::endl;
return 0;
}
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
```
阅读全文