Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4041228
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T12:51:15+00:00 2026-05-20T12:51:15+00:00

I have a service that I had to log on to the local admin

  • 0

I have a service that I had to log on to the local admin to install. The pupose of this service to log when a user is logging in or out to record their username. I finally found a bit of WMI code that I thought would work, but it is still returning Administrator. Why isn’t this working?

var query = new ObjectQuery("SELECT * FROM Win32_Process WHERE Name = 'explorer.exe'");
var explorerProcesses = new ManagementObjectSearcher(query).Get();

foreach (ManagementObject mo in explorerProcesses)
{
    string[] ownerInfo = new string[2];
    mo.InvokeMethod("GetOwner", (object[])ownerInfo);

    userName = String.Concat(ownerInfo[1], @"\", ownerInfo[0]);
}
Console.WriteLine(userName);
Console.ReadLine();

To clarify my question I’m tring to get the currently logged on user but its giving me back Adminstrator the account I used to install the service.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T12:51:15+00:00Added an answer on May 20, 2026 at 12:51 pm

    You should use Service Control Manager Notifications for this. You can configure your service to receive notification events when a user logs on and / or logs off. This allows a service to do interactive user impersonation if the service requires it, but it should give you the info you need for your logging.

    Check out the section “Using Service Control Manager (SCM) Notifications” here http://technet.microsoft.com/en-us/library/cc721961(WS.10).aspx

    edit

    In your Service class override the OnSessionChange event handler to check for logon and logoff events.

    protected override void OnSessionChange(SessionChangeDescription changeDescription)
    {
        base.OnSessionChange(changeDescription);
    
        switch (changeDescription.Reason)
        {
            case SessionChangeReason.SessionLogon:
                // do your logging here
                break;
    
            case SessionChangeReason.SessionLogoff:
                // do your logging here
                break;
        }
    }
    

    edit2:

    class Class1
    {
        [DllImport("Advapi32.dll")]
        static extern bool GetUserName(StringBuilder lpBuffer, ref int nSize);    
        [STAThread]
        static void Main(string[] args)
        {
            StringBuilder Buffer = new StringBuilder(64);
            int nSize=64;
            GetUserName(Buffer, ref nSize);
            Console.WriteLine(Buffer.ToString());
        }
    }
    

    edit3:

    public class InteractiveUser
    {
        [DllImport("wtsapi32.dll", SetLastError = true)]
        static extern bool WTSQueryUserToken(UInt32 sessionId, out IntPtr Token);
    
        [DllImport("kernel32.dll")]
        private static extern UInt32 WTSGetActiveConsoleSessionId();
    
        enum TOKEN_INFORMATION_CLASS
        {
            TokenUser = 1,
            TokenGroups,
            TokenPrivileges,
            TokenOwner,
            TokenPrimaryGroup,
            TokenDefaultDacl,
            TokenSource,
            TokenType,
            TokenImpersonationLevel,
            TokenStatistics,
            TokenRestrictedSids,
            TokenSessionId,
            TokenGroupsAndPrivileges,
            TokenSessionReference,
            TokenSandBoxInert,
            TokenAuditPolicy,
            TokenOrigin
        }
    
        public struct TOKEN_USER 
        { 
            public SID_AND_ATTRIBUTES User; 
        } 
    
        [StructLayout(LayoutKind.Sequential)]
        public struct SID_AND_ATTRIBUTES 
        { 
            public IntPtr Sid; 
            public int Attributes; 
        } 
    
        // Using IntPtr for pSID insted of Byte[]
        [DllImport("advapi32", CharSet=CharSet.Auto, SetLastError=true)]
        static extern bool ConvertSidToStringSid(
            IntPtr pSID, 
            out IntPtr ptrSid);
    
        [DllImport("kernel32.dll")]
        static extern IntPtr LocalFree(IntPtr hMem);
    
        [DllImport("advapi32.dll", SetLastError=true)]
        static extern bool GetTokenInformation(
            IntPtr TokenHandle,
            TOKEN_INFORMATION_CLASS TokenInformationClass,
            IntPtr TokenInformation,
            int TokenInformationLength,
            out int ReturnLength);
    
        private static string GetSID(IntPtr token)
        {
            bool Result;
    
            int TokenInfLength = 0; 
            string sidAsString = String.Empty;
    
            // first call gets lenght of TokenInformation
            Result = GetTokenInformation( token , TOKEN_INFORMATION_CLASS.TokenUser , IntPtr.Zero , TokenInfLength , out TokenInfLength ); 
    
            IntPtr TokenInformation = Marshal.AllocHGlobal( TokenInfLength ) ; 
            Result = GetTokenInformation( token  , TOKEN_INFORMATION_CLASS.TokenUser , TokenInformation , TokenInfLength , out TokenInfLength ) ; 
    
            if ( Result ) 
            {
                TOKEN_USER TokenUser = ( TOKEN_USER )Marshal.PtrToStructure( TokenInformation , typeof( TOKEN_USER ) ) ; 
    
                IntPtr pstr = IntPtr.Zero; 
                Boolean ok = ConvertSidToStringSid( TokenUser.User.Sid  , out pstr ); 
    
                sidAsString = Marshal.PtrToStringAuto( pstr ); 
                LocalFree(pstr);
            }
    
            Marshal.FreeHGlobal( TokenInformation );
    
            return sidAsString;
        }
    
        public static string Account()
        {
            IntPtr token = IntPtr.Zero;
            String account = String.Empty;
    
            if (WTSQueryUserToken(WTSGetActiveConsoleSessionId(), out token))
            {
                String sid = GetSID(token);
                account =
                    new SecurityIdentifier(sid).Translate(typeof(NTAccount)).ToString();
            }
            else
            {
                int err = Marshal.GetLastWin32Error();
                switch (err)
                {
                    case 5:
                        account = "ERROR_ACCESS_DENIED";
                        break;
                    case 87:
                        account = "ERROR_INVALID_PARAMETER";
                        break;
                    case 1008:
                        account = "ERROR_NO_TOKEN";
                        break;
                    case 1314:
                        account = "ERROR_PRIVILEGE_NOT_HELD";
                        break;
                    case 7022:
                        account = "ERROR_CTX_WINSTATION_NOT_FOUND";
                        break;
                    default:
                        account = String.Format("ERROR_{0}", err.ToString());
                        break;
                }
            }
    
            return account;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a windows service that writes out log file entries to an XML
I have modified a working Windows service that had always been starting beforehand. After
Suppose I had a WCF service that I have coded up, like Clemens Vasters's
I have a service that use the tcp binding and this services allows to
I have a data table that is periodically updated by another service. I log
I have my custom continous build that log an error for my tfs service
I have a Service that sends an Intent to my Activity every 0.1 seconds.
I have a service that I would like it to become single instance, because
I have a service that is downloading a file. When the download is done,
I have .Net service that listens on single port over TCP protocol. Clients connect

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.