【发布时间】:2016-12-16 15:30:24
【问题描述】:
我想创建一个功能,如果用户空闲一段时间,它会超时并导航到主页。经过一番研究,我发现 ThreadPoolTimer 应该适合我的需要。测试它我决定使用 10 秒的间隔。
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);
然后我在 tick 函数中调用该函数,如果 IsUserIdle() 等于 true,则使用条件语句然后导航到主页。
public static void Timer_Tick(object sender)
{
if (IsUserIdle() == true)
{
Frame.Navigate(typeof(MainPage));
}
}
但是当我启动它时,什么也没有发生,并且在我设置了几个断点之后,我发现 IsUserIdle() 即使在 10 秒不活动之后也永远不会返回真值。我完全被卡住了,所以任何帮助都将不胜感激。
【问题讨论】:
-
对不起,我打字太快了。原始代码应该是 bool b = (idleTime >= 10); @重力