2012-07-11 68 views
0

我想使用C++获取正在运行的服务的显示名称。我试图使用GetServiceDisplayName函数,但它似乎并没有工作,不知道为什么。如何获取C++中的服务显示名称?

TTServiceBegin(const char *svcName, PFNSERVICE pfnService, bool *svc, PFNTERMINATE pfnTerm, 
int flags, int argc, char *argv[], DWORD dynamiteThreadWaitTime) 
{ 
SC_HANDLE serviceStatusHandle; 
DWORD dwSizeNeeded = 0 ; 
TCHAR* szKeyName = NULL ; 

serviceStatusHandle=OpenSCManager(NULL, SERVICES_ACTIVE_DATABASE ,SC_MANAGER_ALL_ACCESS); 

GetServiceDisplayName(serviceStatusHandle,svcName, NULL, &dwSizeNeeded); 
if(dwSizeNeeded) 
{ 
    szKeyName = new char[dwSizeNeeded+1]; 
    ZeroMemory(szKeyName,dwSizeNeeded+1); 
    if(GetServiceDisplayName(serviceStatusHandle ,svcName,szKeyName,&dwSizeNeeded)!=0) 
    { 
     MessageBox(0,szKeyName,"Got the key name",0); 
    } 


}   

当我运行这段代码,怎么看都看szKeyName的价值在我的调试器,它进入的消息框,如果块,但从来没有显示消息框。不知道为什么?

无论如何得到这个工作得到服务的显示名称或任何其他/更简单的方式来完成这项任务?

回答

1

消息框在Windows Vista和更高版本上将不可见,因为服务运行在单独的会话(Session 0 Isolation)中,因为该更改无法访问桌面,因此消息框不会显示给您,登录的用户。

在Window XP和更早的版本,你需要剔下日志中Allow service to interact with desktop复选框,在服务的属性标签对话框为您服务,使消息框出现。

相反,你可以出来写服务名称到一个文件或运行一个接受服务的名称来查询,并把它查询并显示服务名称的用户应用程序(我只是试图与发布的代码和它的工作原理正确显示消息框)。

+0

但不应该它仍然出现,当我只是调试代码?我不能让它显示,当我调试,甚至无法获得szKeyName的值,即使当我看它它说它无法找到指定的符号 – Bullsfan127 2012-07-11 15:44:28

+0

@ Bullsfan127,我不熟悉调试器,所以不能对此评论。我用''TermService''为服务名尝试了它,并正确显示了一个包含'“终端服务”'的消息框。 – hmjd 2012-07-11 15:46:36

1

您需要使用WTSSendMessage而不是MessageBox与活动会话进行交互。

WTS_SESSION_INFO* pSessionInfo = NULL;   
DWORD dwSessionsCount = 0; 
if(WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSessionInfo, &dwSessionsCount)) 
{ 
    for(int i=0; i<(int)dwSessionsCount; i++) 
    { 
     WTS_SESSION_INFO &si = pSessionInfo[i]; 
     if(si.State == WTSActive) 
     {              
      DWORD dwIdCurrentSession = si.SessionId; 

      std::string strTitle = "Hello"; 
      std::string strMessage = "This is a message from the service"; 

      DWORD dwMsgBoxRetValue = 0; 
      if(WTSSendMessage(
       WTS_CURRENT_SERVER_HANDLE, 
       dwIdCurrentSession, 
       (char*)strTitle.c_str(), 
       strTitle.size(), 
       (char*)strMessage.c_str(), 
       strMessage.size(), 
       MB_RETRYCANCEL | MB_ICONINFORMATION | MB_TOPMOST, 
       60000, 
       &dwMsgBoxRetValue, 
       TRUE)) 
      { 

       switch(dwMsgBoxRetValue) 
       { 
        case IDTIMEOUT: 
         // Deal with TimeOut... 
         break; 
        case IDCANCEL:   
         // Deal With Cancel.... 
         break; 
       }    
      } 
      else 
      { 
       // Deal With Error 
      } 

      break; 
     } 
    } 

    WTSFreeMemory(pSessionInfo);  
} 
相关问题