在codeproject里找了许久,发现这样一个VC下载文件并显示进度条的源码,于是添加了些中文注释:
1、下载线程函数:
- UINT DownloadFile(LPVOID pParam)
- {
- CWnd* pwnd = AfxGetMainWnd();
- CProgressCtrl* m_Prog = (CProgressCtrl*)pwnd->GetDlgItem(IDC_PROGRESS1);
- CButton* bStart = (CButton*)pwnd->GetDlgItem(IDB_BTN_START);
-
- char filebuf[512];
- CInternetSession netSession;
- CStdioFile *fTargFile;
- int outfs;
- CString szFile,FileSize,KBin,KBsec,NewName,Perc;
-
- try
- {
- pwnd->GetDlgItemText(IDC_EDIT1,szFile);
- pwnd->SetDlgItemText(IDC_STAT,"正在校验下载地址...");
- fTargFile = netSession.OpenURL(szFile,1,INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD);
- nDownloaded = 1;
-
- COleDateTime dlStart = COleDateTime::GetCurrentTime();
- int filesize = fTargFile->SeekToEnd();
- fTargFile->SeekToBegin();
- outfs = filesize / 1024;
- FileSize.Format("%d",outfs);
-
-
- CFile fDestFile(fTargFile->GetFileName(), CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);
- int byteswrite;
- int pos = 0;
- int nperc,kbrecv;
- double secs,kbsec;
-
-
- NewName = fTargFile->GetFileName();
-
- if(fTargFile->GetFileName().GetLength() >= 10)
- {
- NewName = fTargFile->GetFileName().Mid(0,7);
- NewName = NewName + "...";
- }
-
- pwnd->SetDlgItemText(IDC_STAT,"正在下载...");
- m_Prog->SetRange32(0,filesize);
-
- while (byteswrite = fTargFile->Read(filebuf, 512))
- {
- if(nTerminate == 1)
- {
- fDestFile.Close();
- fTargFile->Close();
- delete fTargFile;
- pwnd->SetDlgItemText(IDC_STAT,"下载时已被用户取消!");
- AfxEndThread(0);
- }
-
-
- COleDateTimeSpan dlElapsed = COleDateTime::GetCurrentTime() - dlStart;
- secs = dlElapsed.GetTotalSeconds();
- pos = pos + byteswrite;
- fDestFile.Write(filebuf, byteswrite);
- m_Prog->SetPos(pos);
-
- nperc = pos * 100 / filesize;
- kbrecv = pos / 1024;
- kbsec = kbrecv / secs;
-
- Perc.Format("%d",nperc);
- KBin.Format("%d",kbrecv);
- KBsec.Format("%d",(int)kbsec);
-
- pwnd->SetDlgItemText(IDC_EDIT_FILESIZE,FileSize + "KB");
- pwnd->SetDlgItemText(IDC_EDIT_SIZEOK,KBin + "KB");
- pwnd->SetDlgItemText(IDC_EDIT2,KBsec + "KB/秒");
- pwnd->SetDlgItemText(IDC_EDIT4,Perc + "%");
- }
-
- fDestFile.Close();
- }
-
- catch(CInternetException *IE)
- {
- CString strerror;
- TCHAR error[255];
-
- IE->GetErrorMessage(error,255);
- strerror = error;
-
- pwnd->SetDlgItemText(IDC_STAT,strerror);
- pwnd->SetDlgItemText(IDB_BTN_STOP,"Exit");
- nDownloaded = 0;
- delete fTargFile;
- IE->Delete();
- }
-
- pwnd->SetDlgItemText(IDC_EDIT2,"Kb/秒");
- pwnd->SetDlgItemText(IDC_EDIT3,"Loading...");
- pwnd->SetDlgItemText(IDC_EDIT4,"0%");
-
- delete fTargFile;
- if(nDownloaded == 1)
- {
- pwnd->SetDlgItemText(IDC_STAT,"下载完成!");
- bStart->EnableWindow(TRUE);
- }
- return 0;
- }
2、程序运行效果:
3、源码下载: