为了合理的利用CPU资源,微软的游戏循环(摘自DirectX9 SDK demo)如下:
INT CD3DApplication::Run()
{
// Load keyboard accelerators
HACCEL hAccel = LoadAccelerators( NULL, MAKEINTRESOURCE(IDR_MAIN_ACCEL) );
// Now we're ready to recieve and process Windows messages.
bool bGotMsg;
MSG msg;
msg.message = WM_NULL;
PeekMessage( &msg, NULL, 0U, 0U, PM_NOREMOVE );
while( WM_QUIT != msg.message )
{
// Use PeekMessage() if the app is active, so we can use idle time to
// render the scene. Else, use GetMessage() to avoid eating CPU time.
if( m_bActive )
bGotMsg = ( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) != 0 );
else
bGotMsg = ( GetMessage( &msg, NULL, 0U, 0U ) != 0 );
if( bGotMsg )
{
// Translate and dispatch the message
if( hAccel == NULL || m_hWnd == NULL ||
0 == TranslateAccelerator( m_hWnd, hAccel, &msg ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
else
{
if( m_bDeviceLost )
{
// Yield some CPU time to other processes
Sleep( 100 ); // 100 milliseconds
}
// Render a frame during idle time (no messages are waiting)
if( m_bActive )
{
if( FAILED( Render3DEnvironment() ) )
SendMessage( m_hWnd, WM_CLOSE, 0, 0 );
}
}
}
if( hAccel != NULL )
DestroyAcceleratorTable( hAccel );
return (INT)msg.wParam;
}