风神

悟空。。。。。。。。。
posts - 5, comments - 6, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

实现程序自己更新自己

Posted on 2008-12-16 17:56 风神 阅读(2346) 评论(2)  编辑 收藏 引用 所属分类: 程序点滴
以前做了个自动更新程序,后来把这个自动更新程序更新了,但是当时没有设计让自动更新程序来更新自己,这次就把这个功能加到里面了。在添加这个功能的时候,在网上搜了一下,已经有很多这方面的资料,我最后用了批处理来完成的。
设计思路:
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 }

程序经过我的一番测试,暂时没有出现不良反应。希望对有这方面需求的朋友能有所借鉴,程序写的比较简单,如果有什么改进的地方或是有更好的办法,希望能及时的告知,谢谢。

Feedback

# re: 实现程序自己更新自己  回复  更多评论   

2008-12-17 09:34 by 代李
貌似 可以把正在运行的程序名字name_old.exe给改掉name_bak.exe,把新程序 更名为name.exe
下次启动的时候还是启动name.exe

# re: 实现程序自己更新自己  回复  更多评论   

2008-12-17 23:28 by 肥仔
批处理实现不了太复查的更新逻辑,这个是弱点

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理