我想做一个功能,如果用户闲置一段时间,会超时并导航到主页面。经过一番研究,我发现ThreadPoolTimer应该适合我的需求。测试它我决定使用10秒的时间间隔。如何检查用户是否在UWP上空闲?
timer =ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick,TimeSpan.FromSeconds(10));
而这就是我无所适从的地方。我找不到一种方法来检查UWP上的用户输入,而无需单独检查PointerPressed,PointerExited等。因此,我做了一些更深入的挖掘,并且发现了一段代码,如果用户想要给你一个布尔值闲置或不闲。
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);
我然后调用打钩功能的功能和使用条件语句如果IsUserIdle()等于真然后导航到主页。
public static void Timer_Tick(object sender)
{
if (IsUserIdle() == true)
{
Frame.Navigate(typeof(MainPage));
}
}
但是,当我开始也没有任何反应,之后我设置几个断点我发现IsUserIdle()从来没有后闲置10秒返回真值。我完全卡住,所以任何帮助将不胜感激。
对不起,我输入得太快了。原始代码应该是bool b =(idleTime> = 10); @gravity –