http://www.vckbase.com/index.php/wv/94
如何在服务(Service)程序中显示对话框
服务程序(Service)一般是不能和用户进行交互的,所以他一般是不能显示窗口的。要和用户进行交互(如显示窗口),我们必须打开用户WinSta0和desktop,下面的这段代码就是打开上述两个,并显示一个dialog:
BOOL CServiceModule::ShowMsgDlg(void)
{
HDESK hdeskCurrent;
HDESK hdesk;
HWINSTA hwinstaCurrent;
HWINSTA hwinsta;
hwinstaCurrent = GetProcessWindowStation();
if (hwinstaCurrent == NULL){
LogEvent(_T("get window station err"));
return FALSE;
}
hdeskCurrent = GetThreadDesktop(GetCurrentThreadId());
if (hdeskCurrent == NULL){
LogEvent(_T("get window desktop err"));
return FALSE;
}
//打开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 FALSE;
}
if (!SetProcessWindowStation(hwinsta)){
LogEvent(_T("Set window station err"));
return FALSE;
}
//打开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 FALSE;
}
SetThreadDesktop(hdesk);
//到这一步,我们获取了和用户交互(如显示窗口)的权利
CMsgDlg dlgMsg;
//显示一个dialog
dlgMsg.DoModal();
if (!SetProcessWindowStation(hwinstaCurrent))
return FALSE;
if (!SetThreadDesktop(hdeskCurrent))
return FALSE;
if (!CloseWindowStation(hwinsta))
return FALSE;
if (!CloseDesktop(hdesk))
return FALSE;
return TRUE;
}