17,740
社区成员
发帖
与我相关
我的任务
分享
namespace Enginev1._0
{
//定义消息结构,用于PeekMessage填充
[StructLayout(LayoutKind.Sequential)]
public struct Message
{
public IntPtr hWnd;
public int msg;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
public Point p;
}
public class FastLoop
{
public delegate void LoopCallback(double elapsedTime); //定义委托
private readonly LoopCallback _callback; //实例化委托
private readonly PreciseTimer _timer = new PreciseTimer(); //实例精确计时器
//构造函数
public FastLoop(LoopCallback callback)
{
_callback = callback;
Application.Idle += OnApplicationEnterIdle;
}
#region 引入C函数PeekMessage
[SuppressUnmanagedCodeSecurity]
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool PeekMessage(
out Message msg,
IntPtr hWnd,
uint messageFilterMin,
uint messageFilterMax,
uint flags);
#endregion
//这个方法检查了事件队列
private void OnApplicationEnterIdle(object sender, EventArgs e)
{
while (IsAppStillIdle())
{
_callback(_timer.GetElapsedTime());
}
}
//这个方法没有检查事件队列
//private void OnApplicationEnterIdle1 ( object sender, EventArgs e )
//{
// _callback (_timer.GetElapsedTime ());
//}
//这个方法用来判断程序是否进入空闲状态,True=空闲 ,False=不空闲
private static bool IsAppStillIdle()
{
Message msg;
return !PeekMessage(out msg, IntPtr.Zero, 0, 0, 0);
}
}
public class PreciseTimer
{
private long _previousElapsedTime;
private readonly long _ticksPerSecond;
public PreciseTimer()
{
QueryPerformanceFrequency(ref _ticksPerSecond);
GetElapsedTime();
}
[SuppressUnmanagedCodeSecurity]
[DllImport("kernel32")]
private static extern bool QueryPerformanceFrequency(ref long performanceFrequency);
[SuppressUnmanagedCodeSecurity]
[DllImport("kernel32")]
private static extern bool QueryPerformanceCounter(ref long performanceCount);
public double GetElapsedTime()
{
long time = 0;
QueryPerformanceCounter(ref time);
var elapsedTime = (time - _previousElapsedTime)/(double) _ticksPerSecond;
_previousElapsedTime = time;
return elapsedTime;
}
}