• 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
                        }
    

  • posted on 2011-04-13 11:04  Black Bean  阅读(374)  评论(0编辑  收藏  举报