2012-07-11 31 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);  
} 
相關問題