分类: C/C++
2008-03-17 17:14:27
服务程序(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; } |
运行:编译生成guiser.exe, 运行guiser /service, 然后在控制面板的服务中启动该服务,将会出现一个对话框! 上述程序在win2000 professional + VC6.0 + Sp5.0 + Platform SDK 2001.8编译运行通过 如有编译不通过,请下载最新的Platform SDK |