I have a program that can be run as a simple console application or can be registered as Windows Service. I want to detect in main()
function the current running context:
#include <windows.h>
BOOL IsWindowsService()
{
???
}
int main(int argc, char** argv)
{
if (IsWindowsService())
{
// Running as Windows Service...
RunService();
return;
}
// Running as console application...
return 0;
}
The main use-case is to have a single exe file that can be installed and run as a Windows Service with '--install' and '--start' arguments or executed without any parameters in console mode (e.g. from VS debugger).
Can you help me with a possible implementation of IsWindowsService()
function?
int __stdcall wWinMain(HINSTANCE, HINSTANCE, LPWSTR, int)
{
SERVICE_TABLE_ENTRY ServiceTable[] =
{
{ SERVICE_NAME,(LPSERVICE_MAIN_FUNCTION)ServiceMain },
{ NULL,NULL }
};
if (StartServiceCtrlDispatcher(ServiceTable))
//service
else app; // last error ERROR_FAILED_SERVICE_CONTROLLER_CONNECT
}
VOID WINAPI ServiceMain(DWORD argc, LPTSTR *argv)
{...}
Documentation https://learn.microsoft.com/en-us/windows/desktop/api/winsvc/nf-winsvc-startservicectrldispatchera