avr地方业务中有一个dba_bjldnw工具要在服务器上运行着.一旦断开业务即中止.需要写一个守护程序监视它,
一旦发现关闭了即重新启动.
为了防止守护程序本身被用户关闭,所以我打算做一个windows服务在后台运行.每5分钟列举一个当前系统进程,如果
没有发现dba_bjldnw.exe则重新启动.
问题是windows服务不是窗口进程,在这个进程中调用shellexecute打开的应用程序也是在后台运行,不能显示在当前窗口中.
后来搜索到可以在windows服务中打开窗口程序的方法.就是打开用户winsta0和desktop,取得和用户交互的权限后再打开窗口进程,果然可以在windows服务中打开窗口进程了:
hinstance hprocesssnap = null;
processentry32 pe32 = {0};
//获取进程的内存镜照
hprocesssnap = (hinstance) ::createtoolhelp32snapshot(th32cs_snapprocess,0);
if(hprocesssnap == (handle) -1) return ;
pe32.dwsize = sizeof(processentry32);
dword flag = 0;
cstring theprocssname = "dba_bjldnw.exe";
//列举进程
if(::process32first(hprocesssnap,&pe32)){
do{
if(!theprocssname.comparenocase(pe32.szexefile)){
flag = 1;
break;
}
}
while(process32next(hprocesssnap,&pe32));
}
::closehandle(hprocesssnap);
if(!flag){ //如果没有找到
hdesk hdeskcurrent;
hdesk hdesk;
hwinsta hwinstacurrent;
hwinsta hwinsta;
hwinstacurrent = getprocesswindowstation();
if (hwinstacurrent == null){
logevent(_t("get window station err"));
return ;
}
hdeskcurrent = getthreaddesktop(getcurrentthreadid());
if (hdeskcurrent == null){
logevent(_t("get window desktop err"));
return ;
}
//打开用户的winsta0
hwinsta = openwindowstation("winsta0", false,
winsta_accessclipboard |
winsta_accessglobalatoms |
winsta_createdesktop |
winsta_enumdesktops |
winsta_enumerate |
winsta_exitwindows |
winsta_readattributes |
winsta_readscreen |
winsta_writeattributes);
if (hwinsta == null){
logevent(_t("open window station err"));
return ;
}
if (!setprocesswindowstation(hwinsta)){
logevent(_t("set window station err"));
return ;
}
//打开desktop
hdesk = opendesktop("default", 0, false,
desktop_createmenu |
desktop_createwindow |
desktop_enumerate |
desktop_hookcontrol |
desktop_journalplayback |
desktop_journalrecord |
desktop_readobjects |
desktop_switchdesktop |
desktop_writeobjects);
if (hdesk == null){
logevent(_t("open desktop err"));
return;
}
setthreaddesktop(hdesk);
::shellexecute(0,null,"f:\\ivrtj\\dba\\dba_bjldnw.exe",null,null,sw_maximize);
cstring msg = "dba_bjldnw.exe 被重启动";
logevent(msg);
setprocesswindowstation(hwinstacurrent);
setthreaddesktop(hdeskcurrent);
closewindowstation(hwinsta);
closedesktop(hdesk);
}
服务安装后一定要注意,右键->属性->登录,选择 本地系统帐户下面的允许服务与桌面交互打勾.
文章整理:西部数码--专业提供域名注册、虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!


