在手持終端應用程序需要實時連接服務器,而手持設備默認在5分鐘後自動跳到休眠狀態,雖然可以在設備電源高級選項中設置手持設備從不休眠,但是每次刷機後都需要設置,而且在不運行程序時也是始終不休眠,這樣對手持終端的電池的壽命有影響,在這裡通過調用系統函數實現使手持終端在開啟程序後始終不休眠狀態。代碼如下:
[csharp]
using System.Runtime.InteropServices;
using Microsoft.Win32;
[DllImport("CoreDll.dll")]
private static extern void SystemIdleTimerReset();
private static int nDisableSleepCalls = 0;
private static System.Threading.Timer preventSleepTimer = null;
private static void PokeDeviceToKeepAwake(object extra)
{
try
{
SystemIdleTimerReset();//調用系統函數,使系統不休眠
}
catch (Exception e)
{
// TODO
}
}
/**/
/// <summary>
/// </summary>
public static void DisableDeviceSleep()
{
nDisableSleepCalls++;
if (nDisableSleepCalls == 1)
{
//Debug.Assert(preventSleepTimer == null);
preventSleepTimer = new System.Threading.Timer
(new System.Threading.TimerCallback(PokeDeviceToKeepAwake),
null, 0, 30 * 1000);
}
}
private void FrmMain_Load(object sender, EventArgs e)
{
DisableDeviceSleep();//在程序創建時開啟刷新線程 }
摘自 #Define