如何从Universal Windows App(UWP)知道Windows屏幕是否被锁定。我有任何API或方法吗?

问题描述 投票:0回答:1

Similar question

以及其他示例:does this solution work for uwp? Or it's only for desktop apps

“只要锁定屏幕出现,只要该应用程序中没有扩展执行会话等活动,该应用程序也将被暂停。

[当应用暂停时,它会调用Application.Suspending事件。 Visual Studio的UWP项目模板为该事件提供了一个处理程序,称为App.xaml.cs中的OnSuspending。在Windows 10版本1607之前,您需要在此处放置代码以保存状态。现在,建议您如上所述进入背景状态时保存您的状态。“

根据microsoft docs,当出现锁定屏幕时,应用程序将转到App.xaml.cs中的“ OnSuspending()”。

所以我想我们写的用来检查屏幕是否被锁定的任何代码都应该写在“ OnSuspending()”中。

how can this be used to solve our problem?

uwp win-universal-app uwp-xaml windows-10-universal windows-community-toolkit
1个回答
0
投票

[不幸的是,UWP平台中没有这样的api可以用来检测锁定的屏幕。在检查了您提到的案例链接之后,我认为您可以使用桌面扩展来解决问题,其核心理论是通过桌面扩展中的SystemEvents.SessionSwitch事件来监听屏幕锁定行为,并使用AppSerivce将标志消息发送给UWP客户端。我已经为您实现了代码示例,请检查此link。此代码示例基于@Stefan的博客制作。有关更多详细信息,请搜索UWP中的全局热键注册博客。

class LockScreenAppContext : ApplicationContext
{

    private Process process = null;
    private bool LockScreenInProgress = false;

    public LockScreenAppContext()
    {
        int processId = (int)ApplicationData.Current.LocalSettings.Values["processId"];
        process = Process.GetProcessById(processId);
        process.EnableRaisingEvents = true;
        process.Exited += DesktopExtensionAppContext_Exited;
        SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);

    }

    private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
    {
        switch (e.Reason)
        {

            case SessionSwitchReason.SessionLock:
                SentMessage(true);
                break;
            case SessionSwitchReason.SessionUnlock:
                SentMessage(false);
                break;
        }
    }

    private async void SentMessage(bool isLocked)
    {
        ValueSet ScreebLocked = new ValueSet();
        ScreebLocked.Add("Lock", isLocked);

        AppServiceConnection connection = new AppServiceConnection();
        connection.PackageFamilyName = Package.Current.Id.FamilyName;
        connection.AppServiceName = "LockScreenConnection";
        AppServiceConnectionStatus status = await connection.OpenAsync();
        if (status != AppServiceConnectionStatus.Success)
        {
            Debug.WriteLine(status);
            Application.Exit();
        }
        connection.ServiceClosed += Connection_ServiceClosed;
        AppServiceResponse response = await connection.SendMessageAsync(ScreebLocked);
    }

    private void DesktopExtensionAppContext_Exited(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void Connection_ServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args)
    {
        Debug.WriteLine("Connection_ServiceClosed");
        LockScreenInProgress = false;
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.