Подтвердить что ты не робот

Предотвращать переполнение окон во время работы моей программы?

Мне нужно остановить окна от сна, когда моя программа запущена.

И я не только хочу предотвратить таймер сна, но также хочу отменить событие сна, если я нажму кнопку спящего режима или каким-либо другим способом активно скажу компьютеру спать. Поэтому SetThreadExecutionState недостаточно.

Или... На самом деле мне не нужно полностью предотвращать сон, задерживайте его 5-10 секунд, чтобы моя программа завершила задачу.

(Я знаю, что это плохое поведение программы, но это только для личного использования.)

4b9b3361

Ответ 1

У меня возникла проблема с аппаратным устройством, подключенным через usb. XP/Vista будет спать/спящий режим прямо посередине... Великий, вы говорите, когда он возобновляется, он может просто продолжить. Если оборудование все еще подключено!!! У пользователей есть привычка вытаскивать кабели, когда им это нравится.

Вам нужно обрабатывать XP и Vista​​p >

В XP ловушка WM_POWERBROADCAST и найдите файл PBT_APMQUERYSUSPEND.

   // See if bit 1 is set, this means that you can send a deny while we are busy
   if (message.LParam & 0x1)
   {
      // send the deny message
      return BROADCAST_QUERY_DENY;
   } // if
   else
   {
      return TRUE;
   } // else

В Vista используется SetThreadExecutionState, как это

// try this for vista, it will fail on XP
if (SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED) == NULL)
{
   // try XP variant as well just to make sure 
   SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
}  // if 

и когда приложение закончило, верните его в нормальное

// set state back to normal
SetThreadExecutionState(ES_CONTINUOUS);

Ответ 2

После рассмотрения vim ответа

"Использование PowerCreateRequest, PowerSetRequest и PowerClearRequest функции является предпочтительным методом. "

с привязкой AvailabilityRequests.docx на msdn, которая утомительна, чтобы в нее проникнуть (слишком много для чтения), я искал в Интернете конкретный пример в , который основан на PowerCreateRequest, и нашел http://go4answers.webhost4life.com/Example/problem-monitor-wakeup-service-windows7-12092.aspx [ОБНОВЛЕНИЕ 2016 - больше не доступно]

Скопировал и адаптировал его под мои нужды (PInvoke of CloseHandle скопирован из msdn):

using System.Runtime.InteropServices;

    #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>
    private 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);
        }
    }

Ответ 5

Используется тот же метод, что и для предотвращения использования заставки. См. Программно предотвратить запуск заставки Windows.

Обратите внимание, что некоторые параметры безопасности могут переопределять это (принудительное блокирование компьютеров по истечении определенного времени).