Question

How to invoke "Log on as a service Properties" window programmatically? Can I do this using the command line and mmc?

Was it helpful?

Solution

As requested in comments, I have some very simple code that will set the username and password of an already registered service. Naturally this needs to be done at service install time which is when you have elevated rights. The code happens to be in Delphi but it should be trivial to port it to another language. The function calls are all Windows API calls and the documentation can be found in MSDN.

SvcMgr := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
if SvcMgr=0 then begin
  RaiseLastOSError;//calls GetLastError and raises appropriate exception 
end;
Try
  //Name is the name of service and is used here to identify the service
  hService := OpenService(SvcMgr, PChar(Name), SC_MANAGER_ALL_ACCESS);
  if hService=0 then begin
    RaiseLastOSError;
  end;
  Try
    if not ChangeServiceConfig(
      hService,
      SERVICE_NO_CHANGE,
      SERVICE_NO_CHANGE,
      SERVICE_NO_CHANGE,
      nil,
      nil,
      nil,
      nil,
      PChar(Username),//PChar just turns a Delphi string into a null-terminated string
      PChar(Password),
      nil
    ) then begin
      RaiseLastOSError;
    end;
    if not ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, @ServiceDescription) then begin
      RaiseLastOSError;
    end;
  Finally
    CloseServiceHandle(hService);
  End;
Finally
  CloseServiceHandle(SvcMgr);
End;

I'm not sure how you are registering your service (you did not say yet) but it's quite possible that the service registration you are doing is already capable of setting username and password.

If you already happen to be calling CreateService during install then that is the point at which username and password should be set.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top