JavaEar 专注于收集分享传播有价值的技术资料

2个回答

    最佳答案
  1. The service executes under the SYSTEM account, so that what you see in the Environment class. The machine name should not be a problem (see Gmoliv's comment). Services execute independently from whoever may be logged on: that's one of the main reasons to have them.

    If you want to find out what users (yes, there may be more than one) may be logged on to your computer, you'll have to use raw Windows API's AFAIK. If you really want this, one way could be to iterate through desktops, open the named desktop, get the associated user of each desktop, and look up the account name of the user (which returns the account name on the local machine). If you only want the user which may see something on screen, use OpenInputDesktop to get a handle instead of iterating through all of them.

    Note that this requires your service to have higher access rights than usual. I'd be a bit suspicious of such a service myself.

  2. 参考答案2
  3. Try this code snippet

    ManagementScope ms = new ManagementScope(@"\\.\root\cimv2");
    ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_ComputerSystem");
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, query);
    foreach(ManagementObject mo in searcher.Get())
    {
        Console.WriteLine(mo["UserName"].ToString());
    }