本主題說明如何使用進度列來指出冗長的檔案剖析作業進度。
您需要知道的事項
技術
先決條件
- 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_ATTRIBUTESNULL-- 會設定預設安全性值。 如果您需要特定的安全性設定,您必須在結構的成員中設定適當的值。 呼叫 sizeof,以設定 LPSECURITY_ATTRIBUTES 結構的正確大小。
如需詳細資訊,請參閱 安全性考慮:Microsoft Windows 控件。
相關主題