在mfc中获取进程所有者名称

时间:2010-10-12 06:19:30

标签: c++ winapi mfc

我想获取已启动给定应用程序的用户名。例如,如果启动Outlook或IE,我需要获取已启动它的用户的名称。这应该是所有Windows操作系统的通用。但是,下面给出的解决方案在管理员和标准用户中都无法在Windows 2003用户中使用。

2 个答案:

答案 0 :(得分:2)

我发现this page提供了恢复进程所有者名称的功能。

这是代码(不是我的代码,我无法测试):

bool ExtractProcessOwner( HANDLE hProcess_i,
                          CString& csOwner_o )
{
   // Get process token
   HANDLE hProcessToken = NULL;
   if ( !::OpenProcessToken( hProcess_i, TOKEN_READ, &hProcessToken ) || !hProcessToken )
   {
      return false;
   }

   // First get size needed, TokenUser indicates we want user information from given token
   DWORD dwProcessTokenInfoAllocSize = 0;
   ::GetTokenInformation(hProcessToken, TokenUser, NULL, 0, &dwProcessTokenInfoAllocSize);

   // Call should have failed due to zero-length buffer.
   if( ::GetLastError() == ERROR_INSUFFICIENT_BUFFER )
   {
      // Allocate buffer for user information in the token.
      PTOKEN_USER pUserToken = reinterpret_cast<ptoken_user>( new BYTE[dwProcessTokenInfoAllocSize] );
      if (pUserToken != NULL)
      {
         // Now get user information in the allocated buffer
         if (::GetTokenInformation( hProcessToken, TokenUser, pUserToken, dwProcessTokenInfoAllocSize, &dwProcessTokenInfoAllocSize ))
         {
            // Some vars that we may need
            SID_NAME_USE   snuSIDNameUse;
            TCHAR          szUser[MAX_PATH] = { 0 };
            DWORD          dwUserNameLength = MAX_PATH;
            TCHAR          szDomain[MAX_PATH] = { 0 };
            DWORD          dwDomainNameLength = MAX_PATH;

            // Retrieve user name and domain name based on user's SID.
            if ( ::LookupAccountSid( NULL,
                                     pUserToken->User.Sid,
                                     szUser,
                                     &dwUserNameLength,
                                     szDomain,
                                     &dwDomainNameLength,
                                     &snuSIDNameUse ))
            {
               // Prepare user name string
               csOwner_o = _T("\\\\");
               csOwner_o += szDomain;
               csOwner_o += _T("\\");
               csOwner_o += szUser;

               // We are done!
               CloseHandle( hProcessToken );
               delete [] pUserToken;

               // We succeeded
               return true;
            }//End if
         }// End if

         delete [] pUserToken;
      }// End if
   }// End if

   CloseHandle( hProcessToken );

   // Oops trouble
   return false;
}// End GetProcessOwner

希望它有所帮助。

答案 1 :(得分:0)

您需要来自WinApi的GetUserName Function