在通用 Windows 平台中使用 SetWaitableTimer

Using SetWaitableTimer in Universal Windows Platform

我在我的 UWP 应用程序中使用 "kernel32.dll" 中的 SetWaitableTimer。由于我的应用程序,我希望计算机从睡眠中唤醒。如果我 运行 应用程序处于调试模式,它就可以工作。如果我 运行 它处于释放模式,则计算机不会唤醒。

我怎样才能让我的应用程序在运行处于实现模式时唤醒计算机?

private void Button_Click(object sender, RoutedEventArgs e)
    {
        Task.Factory.StartNew(SetWaitForWakeUpTime);
    }

    [DllImport("kernel32.dll")]
    public static extern IntPtr CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName);

    [DllImport("kernel32.dll")]
    public static extern bool SetWaitableTimer(IntPtr hTimer, [In] ref long pDueTime, int lPeriod,
                                                IntPtr pfnCompletionRoutine, IntPtr lpArgToCompletionRoutine, bool fResume);

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern Int32 WaitForSingleObject(IntPtr handle, uint milliseconds);

    static IntPtr handle;

    static void SetWaitForWakeUpTime()
    {
        long duetime = -600000000;

        handle = CreateWaitableTimer(IntPtr.Zero, true, "MyWaitabletimer");
        SetWaitableTimer(handle, ref duetime, 0, IntPtr.Zero, IntPtr.Zero, true);
        uint INFINITE = 0xFFFFFFFF;
        int ret = WaitForSingleObject(handle, INFINITE);
    }

Windows 10 通用 Windows 平台 (UWP) 应用程序可以使用 Win32 和 COM API 的子集。选择 API 的这个子集是为了支持 Windows 运行时应用程序的关键场景,这些场景尚未被 Windows 运行时、HTML/CSS 或其他支持的语言或标准所涵盖。 Windows 应用认证工具包确保您的应用仅使用 Win32 和 COM API 的这个子集。 UWP中可以使用的Win32 API请参考Win32 and COM APIs for UWP apps.

不幸的是,CreateWaitableTimerSetWaitableTimer 不在受支持的 API 中。我们不能在 UWP 应用程序中使用它们。对于 UWP 应用程序,它不应该能够将系统从睡眠中唤醒。但是我们可以通过使用 DisplayRequest class.

来防止系统休眠

Apps that show video or run for extended periods without user input can request that the display remain on by calling DisplayRequest::RequestActive. When a display request is activated, the device's display remains on while the app is visible.

有关详细信息,请参阅 备注 of DisplayRequest class

但如果您正在为企业开发应用程序,则可以尝试使用 Brokered Windows Runtime Components. With this, you have the ability to run existing desktop software assets in one process (desktop component) while interacting with this code in a UWP App. For more info, please check this blog