110 lines
3.4 KiB
C#
110 lines
3.4 KiB
C#
using System;
|
||
using System.Runtime.InteropServices;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
using Windows.Media.Control;
|
||
|
||
namespace TimerApp
|
||
{
|
||
public static class NativeMethods
|
||
{
|
||
[StructLayout(LayoutKind.Sequential)]
|
||
struct LASTINPUTINFO
|
||
{
|
||
public static readonly int SizeOf = Marshal.SizeOf(typeof(LASTINPUTINFO));
|
||
|
||
[MarshalAs(UnmanagedType.U4)]
|
||
public UInt32 cbSize;
|
||
[MarshalAs(UnmanagedType.U4)]
|
||
public UInt32 dwTime;
|
||
}
|
||
|
||
[DllImport("user32.dll")]
|
||
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
|
||
|
||
/// <summary>
|
||
/// 获取系统空闲时间(毫秒)
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public static long GetIdleTime()
|
||
{
|
||
LASTINPUTINFO lastInputInfo = new LASTINPUTINFO
|
||
{
|
||
cbSize = (uint)Marshal.SizeOf<LASTINPUTINFO>(),
|
||
dwTime = 0
|
||
};
|
||
|
||
if (GetLastInputInfo(ref lastInputInfo))
|
||
{
|
||
uint tickCount = GetTickCount();
|
||
uint idleMs = unchecked(tickCount - lastInputInfo.dwTime);
|
||
return idleMs;
|
||
}
|
||
|
||
return 0;
|
||
}
|
||
|
||
[DllImport("kernel32.dll")]
|
||
static extern uint GetTickCount();
|
||
|
||
/// <summary>
|
||
/// 检测是否有媒体正在播放(视频或音频)
|
||
/// </summary>
|
||
/// <returns>如果有媒体正在播放返回 true,否则返回 false</returns>
|
||
public static bool IsMediaPlaying()
|
||
{
|
||
EnsureMediaPlaybackStatusFresh();
|
||
return Volatile.Read(ref _mediaPlaying);
|
||
}
|
||
|
||
private static bool _mediaPlaying;
|
||
private static long _mediaLastUpdateMs = -1;
|
||
private static int _mediaUpdateInProgress;
|
||
|
||
private static void EnsureMediaPlaybackStatusFresh()
|
||
{
|
||
long now = Environment.TickCount64;
|
||
long last = Interlocked.Read(ref _mediaLastUpdateMs);
|
||
if (last >= 0 && now - last < 3000)
|
||
{
|
||
return;
|
||
}
|
||
|
||
if (Interlocked.Exchange(ref _mediaUpdateInProgress, 1) == 1)
|
||
{
|
||
return;
|
||
}
|
||
|
||
_ = Task.Run(async () =>
|
||
{
|
||
bool playing = false;
|
||
try
|
||
{
|
||
var sessionManager = await GlobalSystemMediaTransportControlsSessionManager.RequestAsync();
|
||
var sessions = sessionManager.GetSessions();
|
||
|
||
foreach (var session in sessions)
|
||
{
|
||
var playbackInfo = session.GetPlaybackInfo();
|
||
if (playbackInfo.PlaybackStatus == GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing)
|
||
{
|
||
playing = true;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
catch
|
||
{
|
||
playing = false;
|
||
}
|
||
finally
|
||
{
|
||
Volatile.Write(ref _mediaPlaying, playing);
|
||
Interlocked.Exchange(ref _mediaLastUpdateMs, Environment.TickCount64);
|
||
Interlocked.Exchange(ref _mediaUpdateInProgress, 0);
|
||
}
|
||
});
|
||
}
|
||
}
|
||
}
|