Windows 11引入了“焦点”功能,该功能通过启用“请勿打扰”和“提示”图标闪烁和任务栏中应用的锁屏提醒通知,帮助用户最大程度地减少干扰。 本文介绍如何使用 FocusSessionManager API 检测焦点会话当前处于活动状态,或者在焦点会话状态发生更改时接收更新,从而允许自定义应用的行为,以最大程度地减少焦点会话处于活动状态时的干扰。 有关焦点功能的详细信息,请参阅 如何在Windows 11中使用焦点

获取当前焦点会话状态

在访问 FocusSessionManager 的属性之前,请通过检查 IsSupported 属性确保当前设备上支持它。 验证是否支持此功能后,可以通过检查 IsFocusActive 属性来确定焦点会话当前是否处于活动状态。

C++/WinRT if (Windows.UI.Shell.FocusSessionManager.IsSupported) var manager = Windows.UI.Shell.FocusSessionManager.GetDefault(); focusActive = manager.IsFocusActive; if (!focusActive) statusTextBlock.Text = message; // MainWindow.xaml.h Windows::UI::Shell::FocusSessionManager m_focusSessionManager = Windows::UI::Shell::FocusSessionManager::GetDefault(); void UpdateStatusBar(winrt::hstring const& message); // MainWindow.xaml.cpp void MainWindow::UpdateStatusBar(winrt::hstring const& message) auto focusActive = false; if (Windows::UI::Shell::FocusSessionManager::IsSupported()) focusActive = m_focusSessionManager.IsFocusActive(); if (!focusActive) StatusTextBlock().Text(message);

持续监视焦点状态

可以通过注册 IsFocusActiveChanged 事件,在设备上焦点会话状态更改时订阅通知。 在以下示例 中,SetAnimatedGifAutoPlay 是一种应用实现的帮助程序方法,用于更改应用是否基于当前焦点会话状态自动播放动画 gif。

C++/WinRT
protected override void OnNavigatedTo(NavigationEventArgs e)
    if (Windows.UI.Shell.FocusSessionManager.IsSupported)
        var manager = Windows.UI.Shell.FocusSessionManager.GetDefault();
        manager.IsFocusActiveChanged += Manager_IsFocusActiveChanged;
        SetAnimatedGifAutoPlay(true);
private void Manager_IsFocusActiveChanged(Windows.UI.Shell.FocusSessionManager sender, object args)
    if(sender.IsFocusActive)
        SetAnimatedGifAutoPlay(true);
        SetAnimatedGifAutoPlay(false);
// MainWindow.xaml.h
void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
Windows::UI::Shell::FocusSessionManager m_focusSessionManager = Windows::UI::Shell::FocusSessionManager::GetDefault();
winrt::event_token m_focusStateChangedToken;
void OnFocusStateChanged(Windows::UI::Shell::FocusSessionManager const& sender, Windows::Foundation::IInspectable const&);
// MainWindow.xaml.cpp
void MainWindow::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&)
    if (Windows::UI::Shell::FocusSessionManager::IsSupported())
        m_focusStateChangedToken = m_focusSessionManager.IsFocusActiveChanged(
            { get_weak(), &MainWindow::OnFocusStateChanged });
        SetAnimatedGifAutoPlay(true);
void MainWindow::OnFocusStateChanged(Windows::UI::Shell::FocusSessionManager const& sender,
        Windows::Foundation::IInspectable const&)
    auto temp = m_focusSessionManager.IsFocusActive();
    SetAnimatedGifAutoPlay(m_focusSessionManager.IsFocusActive());