Windows Service得到当前用户的名字和域

  • Create a Windows Service project using VB.NET.
  • Open Server Explorer and expand the tree node which says Management Classes.
  • Right click on Processes node and select "Generate Managed Class". This will add a reference to the System.Management namespace.
  • Now import System.Management namespace in your project (Service1.vb).
  • In the OnStart procedure, add the following code: 
  • Dim mc As New ManagementClass("Win32_Process")
    Dim moc As ManagementObjectCollection = mc.GetInstances
    Dim mo As ManagementObject
    Dim processDomain, processUser As String
    
     For Each mo In moc
    
         Dim p As New ROOT.CIMV2.Process(mo)
         p.GetOwner(processDomain, processUser)
    
           If (p.Name.Trim = "explorer.exe") Then
              Return processUser
              Exit For
           End If
      
     Next

    C#   using System.Management;
      
      
    string domainName = string.Empty;
                        string curUserName = string.Empty;
                        string nameCurrent = string.Empty;
                        try
                        {
                            ManagementClass ms = new ManagementClass("Win32_Process");
                            ManagementObjectCollection moc = ms.GetInstances();
                            
    
                            foreach( ManagementObject mo in moc)
                            {
                                ROOT.CIMV2.Process p = new Customization.Service.ROOT.CIMV2.Process(mo);
                                p.GetOwner(out domainName,out curUserName);
                                if(p.Name.Trim() == "explorer.exe")
                                {
                                    nameCurrent = domainName+"\\"+curUserName;
                                    break;
                                }
                            } 
                        }
                        catch
                        {
                            //do nothing
                        }
    

  • 你可能感兴趣的:(windows)