0

I wrote a system level Windows service, from which, I want to get the current logged-on user's name. I tried "GetUserName()" API, but it always returns "SYSTEM", because the service is system level. So, how can I get the current logged-on user's name from this Windows service? Any other Windows API?
The program is written in C++.
Updated:
There is a C# related Q/A. Not sure how it is implemented with C++ Windows API.

Finix
  • 131
  • 14
  • 1
    What do you think you mean by "the" current logged on user? Keep in mind the same Windows API works on terminal servers... – nobody Jul 23 '16 at 18:03
  • Multiple users may be logged on at the same (consider Fast User Switching or a server to which users connect via RDP). Returning only one user might not be sufficient in such cases. – Martin Drab Jul 23 '16 at 22:17
  • @AndrewMedico I understand what you mean. But I find it seems possible for C# to do this. About "the current logged on user", it is indeed confusing. I'm not familiar the C# code. Please see this Q/A: [http://stackoverflow.com/questions/5218778/how-do-i-get-the-currently-logged-username-from-a-windows-service-in-net](http://stackoverflow.com/questions/5218778/how-do-i-get-the-currently-logged-username-from-a-windows-service-in-net) – Finix Jul 24 '16 at 01:01
  • You didn't understand, what Andrew was saying at all. This isn't possible, irrespective of programming language. You cannot fight logic, and win. – IInspectable Jul 24 '16 at 01:36
  • 1
    Thanks @HarryJohnston. I figured out the final answer from your link. 1. Use WTSGetActiveConsoleSessionId() to get the session id frist; 2. Use WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, sessionId, WTSUserName, ppBuffer, &bufferSize) to get the user name. – Finix Jul 24 '16 at 08:59

1 Answers1

-2

Have you tried using getenv("username")?

It's working for me:

#include <iostream>
#include <windows.h>

    int main()
    {
     std::cout << getenv("username") << std::endl;
     return 0;
    }
0x38
  • 11
  • 6