feat: 添加媒体播放检测功能以优化工作状态管理

This commit is contained in:
2026-01-17 13:53:57 +08:00
parent e26c015e09
commit 052aa060cc
3 changed files with 46 additions and 5 deletions

View File

@@ -93,10 +93,13 @@ namespace TimerApp
} }
else else
{ {
// 检测是否有视频/媒体正在播放
bool isMediaPlaying = NativeMethods.IsMediaPlaying();
// 工作/空闲模式逻辑 // 工作/空闲模式逻辑
if (idleTime > IdleThreshold) if (idleTime > IdleThreshold || isMediaPlaying)
{ {
// 用户离开了 // 用户离开了或正在播放视频
if (CurrentState == MonitorState.Working) if (CurrentState == MonitorState.Working)
{ {
// 如果正在工作,但离开了,暂停工作计时? // 如果正在工作,但离开了,暂停工作计时?
@@ -112,10 +115,18 @@ namespace TimerApp
{ {
_accumulatedWorkTime = TimeSpan.Zero; _accumulatedWorkTime = TimeSpan.Zero;
} }
// 如果正在播放视频,不累加工作时间,但保持当前状态
if (isMediaPlaying && CurrentState == MonitorState.Working)
{
// 保持当前剩余时间不变(不累加,也不减少)
TimeSpan remainingWork = WorkDuration - _accumulatedWorkTime;
WorkProgressChanged?.Invoke(this, remainingWork);
}
} }
else else
{ {
// 用户在活动 // 用户在活动且没有播放视频
if (CurrentState == MonitorState.Idle) if (CurrentState == MonitorState.Idle)
{ {
// 从空闲变为工作 // 从空闲变为工作

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Windows.Media.Control;
namespace TimerApp namespace TimerApp
{ {
@@ -48,5 +49,34 @@ namespace TimerApp
[DllImport("kernel32.dll")] [DllImport("kernel32.dll")]
static extern uint GetTickCount(); static extern uint GetTickCount();
/// <summary>
/// 检测是否有媒体正在播放(视频或音频)
/// </summary>
/// <returns>如果有媒体正在播放返回 true否则返回 false</returns>
public static bool IsMediaPlaying()
{
try
{
var sessionManager = GlobalSystemMediaTransportControlsSessionManager.RequestAsync().GetAwaiter().GetResult();
var sessions = sessionManager.GetSessions();
foreach (var session in sessions)
{
var playbackInfo = session.GetPlaybackInfo();
if (playbackInfo.PlaybackStatus == GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing)
{
return true;
}
}
}
catch
{
// 如果 API 调用失败,返回 false保守处理
return false;
}
return false;
}
} }
} }

View File

@@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<TargetFramework>net9.0-windows</TargetFramework> <TargetFramework>net9.0-windows10.0.17763.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms> <UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>