Stephen Kellett
Stephen Kellett

Reputation: 3236

How can I tell if the current process is a service or not (C++, Win32)?

How can I tell if the application my code is running in, is it in a service or an application? Why do I want to know this - I'm writing some code that is injected into the target application and that code has no way of knowing this information up front, so it has to work it out itself.

I cannot rely on any code being called from the service control manager, start, stop, or command line parameters.

I'm currently looking at GetConsoleWindow() which I hope will return NULL for a service (no console) and a window handle for any application (has a console). Not sure how valid this assumption is.

Any ideas for a better solution?

Upvotes: 4

Views: 3941

Answers (5)

Tony Edgecombe
Tony Edgecombe

Reputation: 3915

For Windows Vista or later you can check the session id. Session 0 is reserved for services and non-interactive programs. User sessions start from 1.

Upvotes: 1

Steve Townsend
Steve Townsend

Reputation: 54148

Use WMI to query for Win32_Service instances where 'ProcessId=MyProcessid'. If there is no match, then your process is not a service.

Background on WMI app creation in C++ here.

Upvotes: 1

OldFart
OldFart

Reputation: 2479

Use OpenProcessToken to get the current process token. Then use CheckTokenMembership to see if the token includes the WinServiceSid well-known SID.

Upvotes: -2

Peon the Great
Peon the Great

Reputation: 1319

The assumption of GetConsoleWindow() is not valid.

It seems to me that you care about the context of your process more. Are you asking that if your program is running in service context or the user session? If so, use ProcessIdToSessionId() http://msdn.microsoft.com/en-us/library/aa382990%28v=VS.85%29.aspx to get your session id and you will know it.

Upvotes: 2

kbjorklu
kbjorklu

Reputation: 1398

Search the current process id (GetCurrentProcessId) from the list of all running services (EnumServicesStatusEx)?

Upvotes: 8

Related Questions