Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi am using below code to awake system back from sleep mode..but its not working am not able to figure out the problem can anyone help? Thanks.
C#
#region prevent screensaver, display dimming and automatically sleeping
       POWER_REQUEST_CONTEXT _PowerRequestContext;
       IntPtr _PowerRequest; //HANDLE

       // Availability Request Functions
       [DllImport("kernel32.dll")]
       static extern IntPtr PowerCreateRequest(ref POWER_REQUEST_CONTEXT Context);

       [DllImport("kernel32.dll")]
       static extern bool PowerSetRequest(IntPtr PowerRequestHandle, PowerRequestType RequestType);

       [DllImport("kernel32.dll")]
       static extern bool PowerClearRequest(IntPtr PowerRequestHandle, PowerRequestType RequestType);

       [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
       internal static extern int CloseHandle(IntPtr hObject);



       // Availablity Request Enumerations and Constants
       enum PowerRequestType
       {
           PowerRequestDisplayRequired = 0,
           PowerRequestSystemRequired,
           PowerRequestAwayModeRequired,
           PowerRequestMaximum

       }

       const int POWER_REQUEST_CONTEXT_VERSION = 0;
       const int POWER_REQUEST_CONTEXT_SIMPLE_STRING = 0x1;
       const int POWER_REQUEST_CONTEXT_DETAILED_STRING = 0x2;

       // Availablity Request Structures
       // Note:  Windows defines the POWER_REQUEST_CONTEXT structure with an
       // internal union of SimpleReasonString and Detailed information.
       // To avoid runtime interop issues, this version of
       // POWER_REQUEST_CONTEXT only supports SimpleReasonString.
       // To use the detailed information,
       // define the PowerCreateRequest function with the first
       // parameter of type POWER_REQUEST_CONTEXT_DETAILED.
       [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
       public struct POWER_REQUEST_CONTEXT
       {
           public UInt32 Version;
           public UInt32 Flags;
           [MarshalAs(UnmanagedType.LPWStr)]
           public string
               SimpleReasonString;
       }

       [StructLayout(LayoutKind.Sequential)]
       public struct PowerRequestContextDetailedInformation
       {
           public IntPtr LocalizedReasonModule;
           public UInt32 LocalizedReasonId;
           public UInt32 ReasonStringCount;
           [MarshalAs(UnmanagedType.LPWStr)]
           public string[] ReasonStrings;
       }

       [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
       public struct POWER_REQUEST_CONTEXT_DETAILED
       {
           public UInt32 Version;
           public UInt32 Flags;
           public PowerRequestContextDetailedInformation DetailedInformation;
       }
       #endregion


       /// <summary>
       /// Prevent screensaver, display dimming and power saving. This function wraps PInvokes on Win32 API.
       /// </summary>
       /// <param name="enableConstantDisplayAndPower">True to get a constant display and power - False to clear the settings</param>
       public void EnableConstantDisplayAndPower(bool enableConstantDisplayAndPower)
       {
           if (enableConstantDisplayAndPower)
           {
               //// Set up the diagnostic string
               _PowerRequestContext.Version = POWER_REQUEST_CONTEXT_VERSION;
               _PowerRequestContext.Flags = POWER_REQUEST_CONTEXT_SIMPLE_STRING;
               _PowerRequestContext.SimpleReasonString = "Continuous measurement"; // your reason for changing the power settings;

               //// Create the request, get a handle
               _PowerRequest = PowerCreateRequest(ref _PowerRequestContext);

               // Set the request
               PowerSetRequest(_PowerRequest, PowerRequestType.PowerRequestSystemRequired);
               PowerSetRequest(_PowerRequest, PowerRequestType.PowerRequestDisplayRequired);




           }
           else
           {
               // Clear the request
               PowerClearRequest(_PowerRequest, PowerRequestType.PowerRequestSystemRequired);
               PowerClearRequest(_PowerRequest, PowerRequestType.PowerRequestDisplayRequired);

               CloseHandle(_PowerRequest);
           }
       }
Posted
Updated 4-Apr-20 8:05am
v2
Comments
Dave Kreskowiak 28-Oct-14 9:46am    
Your code is ignoring the return values from those function calls. You might want to look at those and see what the return values mean.
Gayatri Kadam 29-Oct-14 2:44am    
it still goes into sleep mode even if I handle that..
Dave Kreskowiak 29-Oct-14 8:25am    
<SMACK!> WHAT ARE THE RETURN VALUES?!?!?!
Mehdi Gholam 28-Oct-14 10:04am    
Your code will not run when the computer is in sleep mode!
Gayatri Kadam 29-Oct-14 2:44am    
Actually its not working in sleep mode..

1 solution

var powerRequest = IntPtr.Zero;
var powerSuccess = false;

try
{
    Debug.WriteLine("Suspending system sleep");

    // Set up the diagnostic string
    POWER_REQUEST_CONTEXT powerRequestContext;
    powerRequestContext.Version = POWER_REQUEST_CONTEXT_VERSION;
    powerRequestContext.Flags   = POWER_REQUEST_CONTEXT_SIMPLE_STRING;
    powerRequestContext.SimpleReasonString = "Compacting database"; 

    powerRequest = Imports.PowerCreateRequest(ref powerRequestContext);
    if (powerRequest == IntPtr.Zero)
    {
        var error = Marshal.GetLastWin32Error();
        Debug.WriteLine($"{nameof(Imports.PowerCreateRequest)} failed, error={error}");
    }
    else if (! (powerSuccess = Imports.PowerSetRequest(powerRequest, PowerRequestType.PowerRequestSystemRequired)))
    {
        var error = Marshal.GetLastWin32Error();
        Debug.WriteLine($"{nameof(Imports.PowerSetRequest)} failed, error={error}");
    }

    // do something that you don't want interrupted
}
finally
{
    if (powerRequest != IntPtr.Zero)
    {
        Debug.WriteLine("Resuming system sleep");

        // Clear the request
        if (powerSuccess)
        {
            if (! Imports.PowerClearRequest(powerRequest, PowerRequestType.PowerRequestSystemRequired))
            {
                var error = Marshal.GetLastWin32Error();
                Debug.WriteLine($"{nameof(Imports.PowerClearRequest)} failed, error={error}");
            }
        }

        if (! Imports.CloseHandle(powerRequest))
        {
            var error = Marshal.GetLastWin32Error();
            Debug.WriteLine($"{nameof(Imports.CloseHandle)} failed, error={error}");
        }
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900