我想要创建一个函数,如果用户闲置一段时间,则会超时并导航到主页面。经过一番调研,我发现 ThreadPoolTimer 应该满足我的需求。测试后,我决定使用 10 秒的间隔。
timer =ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick,TimeSpan.FromSeconds(10));
这就是我遇到的问题。在不逐个检查PointerPressed,PointerExited等情况下,我无法找到在UWP上检查用户输入的方法。因此,我进行了更多的研究,并找到了一段代码块,据说可以给出一个布尔值来判断用户是否处于空闲状态。
public static uint GetIdleTime()
{
LASTINPUTINFO lastInPut = new LASTINPUTINFO();
lastInPut.cbSize = (uint)Marshal.SizeOf(lastInPut);
GetLastInputInfo(ref lastInPut);
return ((uint)Environment.TickCount - lastInPut.dwTime);
}
public static bool IsUserIdle()
{
uint idleTime = (uint)Environment.TickCount - GetLastInputEventTickCount();
if (idleTime > 0)
{
idleTime = (idleTime / 1000);
}
else
{
idleTime = 0;
}
//user is idle for 10 sec
bool b = (idleTime >= 10);
return b;
}
private static uint GetLastInputEventTickCount()
{
LASTINPUTINFO lii = new LASTINPUTINFO();
lii.cbSize = (uint)Marshal.SizeOf(lii);
lii.dwTime = 0;
uint p = GetLastInputInfo(ref lii) ? lii.dwTime : 0;
return p;
}
[StructLayout(LayoutKind.Sequential)]
private struct LASTINPUTINFO
{
public static readonly int SizeOf = Marshal.SizeOf<LASTINPUTINFO>();
[MarshalAs(UnmanagedType.U4)]
public UInt32 cbSize;
[MarshalAs(UnmanagedType.U4)]
public UInt32 dwTime;
}
[DllImport("user32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
我会尽力进行翻译,请核对以下内容是否符合您的需求:
然后我在tick函数中调用该函数,并使用条件语句:如果IsUserIdle()等于true,则导航到主页面。
public static void Timer_Tick(object sender)
{
if (IsUserIdle() == true)
{
Frame.Navigate(typeof(MainPage));
}
}
但是当我启动它时什么也没有发生,我设置了几个断点后发现即使在10秒的不活动时间后IsUserIdle()从来没有返回过一个真值。我完全陷入困境,所以任何帮助都将不胜感激。