以前做了個自動更新程序,后來把這個自動更新程序更新了,但是當時沒有設計讓自動更新程序來更新自己,這次就把這個功能加到里面了。在添加這個功能的時候,在網上搜了一下,已經有很多這方面的資料,我最后用了批處理來完成的。
設計思路:
1.自動更新程序檢測到網上有新版本的自己時,先從網上下載新版本程序到同一個目錄下,另起個名字保存。
2.在自動更新程序退出時,創建并運行一個批處理文件,來完成以舊換新的功能。
下面是相關的實現部分
1 bool CAutoUpdateDlg::DeleteMyself(void)
2 {
3 //1.創建自己批處理文件
4 CString sbatName,sPath;
5 sPath=m_strAppPath+m_strAppName;
6 sbatName=m_strAppPath+"delete.bat";
7 ofstream outfile(sbatName.GetBuffer());
8 if(outfile)
9 {
10 outfile<<":try"<<endl; //定義標記
11 outfile<<"choice /t 1 /d y >nul"<<endl; //暫停1秒
12 outfile<<"del \""+sPath+"\""<<endl; //刪除原程序文件
13 outfile<<"if exist \""+sPath+"\""+" goto :try"<<endl; //如果刪除失敗,運行到標記try處,循環以上步驟
14 outfile<<"rename "+m_strAppBakName+" "+m_strAppName<<endl; //重命名新文件為程序文件
15 outfile<<"del \""+sbatName+"\""; //刪除批處理文件
16 }
17 outfile.close();
18
19 //2.創建運行批處理的進程,它以空閑優先級創建
20 STARTUPINFO si;
21 PROCESS_INFORMATION pi;
22 ZeroMemory( &si, sizeof(si) );
23 si.cb = sizeof(si);
24 si.dwFlags=STARTF_USESHOWWINDOW;
25 si.wShowWindow=SW_HIDE; //以隱藏狀態運行
26 ZeroMemory( &pi, sizeof(pi) );
27 if( !CreateProcess( NULL, // No module name (use command line).
28 sbatName.GetBuffer(), // Command line.
29 NULL, // Process handle not inheritable.
30 NULL, // Thread handle not inheritable.
31 FALSE, // Set handle inheritance to FALSE.
32 IDLE_PRIORITY_CLASS, // IDLE flags.
33 NULL, // Use parent's environment block.
34 NULL, // Use parent's starting directory.
35 &si, // Pointer to STARTUPINFO structure.
36 &pi ) // Pointer to PROCESS_INFORMATION structure.
37 )
38 {
39 CloseHandle(pi.hThread);
40 CloseHandle(pi.hProcess);
41 return false;
42 }
43 return true;
44 }
程序經過我的一番測試,暫時沒有出現不良反應。希望對有這方面需求的朋友能有所借鑒,程序寫的比較簡單,如果有什么改進的地方或是有更好的辦法,希望能及時的告知,謝謝。