本主题介绍如何使用进度条来指示漫长的文件解析操作的进度。
需要了解的事项
技术
先决条件
- C/C++
- Windows 用户界面编程
说明
创建进度条控件
以下示例代码创建一个进度条,并将其放置在父窗口工作区的底部。 进度条的高度基于滚动条中使用的箭头位图的高度。 该范围基于文件的大小除以 2,048,即从文件读取的每个数据“区块”的大小。 该示例还设置一个增量,并在解析每个区块后按增量推进进度条的当前位置。
// ParseALargeFile - uses a progress bar to indicate the progress of a parsing operation.
//
// Returns TRUE if successful, or FALSE otherwise.
//
// hwndParent - parent window of the progress bar.
//
// lpszFileName - name of the file to parse.
//
// Global variable
// g_hinst - instance handle.
//
extern HINSTANCE g_hinst;
BOOL ParseALargeFile(HWND hwndParent, LPTSTR lpszFileName)
{
RECT rcClient; // Client area of parent window.
int cyVScroll; // Height of scroll bar arrow.
HWND hwndPB; // Handle of progress bar.
HANDLE hFile; // Handle of file.
DWORD cb; // Size of file and count of bytes read.
LPCH pch; // Address of data read from file.
LPCH pchTmp; // Temporary pointer.
// Ensure that the common control DLL is loaded, and create a progress bar
// along the bottom of the client area of the parent window.
//
// Base the height of the progress bar on the height of a scroll bar arrow.
InitCommonControls();
GetClientRect(hwndParent, &rcClient);
cyVScroll = GetSystemMetrics(SM_CYVSCROLL);
hwndPB = CreateWindowEx(0, PROGRESS_CLASS, (LPTSTR) NULL,
WS_CHILD | WS_VISIBLE, rcClient.left,
rcClient.bottom - cyVScroll,
rcClient.right, cyVScroll,
hwndParent, (HMENU) 0, g_hinst, NULL);
// Open the file for reading, and retrieve the size of the file.
hFile = CreateFile(lpszFileName, GENERIC_READ, FILE_SHARE_READ,
(LPSECURITY_ATTRIBUTES) NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, (HANDLE) NULL);
if (hFile == (HANDLE) INVALID_HANDLE_VALUE)
return FALSE;
cb = GetFileSize(hFile, (LPDWORD) NULL);
// Set the range and increment of the progress bar.
SendMessage(hwndPB, PBM_SETRANGE, 0, MAKELPARAM(0, cb / 2048));
SendMessage(hwndPB, PBM_SETSTEP, (WPARAM) 1, 0);
// Parse the file.
pch = (LPCH) LocalAlloc(LPTR, sizeof(char) * 2048);
pchTmp = pch;
do {
ReadFile(hFile, pchTmp, sizeof(char) * 2048, &cb, (LPOVERLAPPED) NULL);
// TODO: Write an error handler to check that all the
// requested data was read.
//
// Include here any code that parses the
// file.
//
//
//
// Advance the current position of the progress bar by the increment.
SendMessage(hwndPB, PBM_STEPIT, 0, 0);
} while (cb);
CloseHandle((HANDLE) hFile);
DestroyWindow(hwndPB);
return TRUE;
}
注解
必须确保正确使用 ReadFile 函数,以确保应用程序的安全性。 例如,在示例代码中,应进行检查以确保 ReadFile
实际读取所有请求的数据。
另请注意,CreateFile—(LPSECURITY_ATTRIBUTES)NULL 的第四个参数—设置默认安全值。 如果需要特定的安全设置,则必须在结构的成员中设置相应的值。 调用 sizeof 以设置 LPSECURITY_ATTRIBUTES 结构的正确大小。
有关更多信息,请参阅安全注意事项:Microsoft Windows 控件。
相关主题