Windows service cannot set DISPLAY_REQUIRED

Ren, Ken 0 Reputation points
2024-07-02T09:14:03.3433333+00:00

I am developing a windows service application which is able to control the sleep/screen status.I use the function:

SetThreadExecutionState(ExecutionState.ES_SYSTEM_REQUIRED | ExecutionState.ES_DISPLAY_REQUIRED | ExecutionState.ES_CONTINUOUS);

I found out if i run the console application directly, the status could be changed as expected.

But if i run the application as a windows service, the ES_DISPLAY_REQUIRED is missing while the ES_SYSTEM_REQUIRED and ES_CONTINOUS is there.

I already marked the service as interactive.

No exception was thrown and return value is last status.

Is there anyway i could change this behaviour?

Windows
Windows
A family of Microsoft operating systems that run across personal computers, tablets, laptops, phones, internet of things devices, self-contained mixed reality headsets, large collaboration screens, and other devices.
5,047 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Hania Lian 10,931 Reputation points Microsoft Vendor
    2024-07-04T02:46:01.99+00:00

    Hello,

    When running a Windows service, there are certain limitations and differences in the way the system behaves compared to running a console application.

    One possibility is that the behavior is different because the service is running in a non-interactive session. Even if you have marked the service as interactive, starting from Windows Vista, interactive services are no longer supported. This means that the service runs in a separate session and does not have access to the desktop and user-specific features, including the display.

    To work around this limitation, you can try the following approaches:

    Use the Service Control Manager (SCM) to detect user logon/logoff events and run a separate user-mode process that calls SetThreadExecutionState when a user is logged on.

    Instead of using a Windows service, you can create a separate user-mode application that runs in the user’s session and uses SetThreadExecutionState to control the system’s sleep and display behavior.

    Consider using other methods or APIs that may be available for achieving the desired behavior in the context of a Windows service.

    Best Regards,

    Hania Lian

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.

     

    0 comments No comments