IVR地方业务中有一个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);
}
服务安装后一定要注意,右键->属性->登录,选择 本地系统帐户下面的允许服务与桌面交互打勾.