(recycle from past) game loop update in c#

Game loop in C#
Game update loop is a problem in C#. Of course, first thought of us must be attach the Idle event of Application, like this.

1
2
3
4
5
6
7
8
9
Application.Idle += new EventHandler(OnAppIdle);
Application.Run(mMainFrame);
static void OnAppIdle(object sender, EventArgs e)
{
//Do some game loop update here
mMainFrame.DoUpdate();
}

It seems reasonable, we register a listener to Idle event, so it must be run OnAppIdle while application idle, right?

Partially right.

When the application keep going, it will only get message while “When application need to be updated”. It means, therefore, if you leave mouse out of this application form(so no MouseMove event sent), it will totally stop, so it will be updated only when getting some message : such like OnMouseMove….etc.

Solution is from Rich, and he found it in sample of MDX applications. Don’t ask me how to do it, just need to know use this way to keep the game loop.

We might discuss this in later post =3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
static class Program
{
///
/// The main entry point for the application.
///
///
static SceneEditorMain mMainFrame;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
mMainFrame = new SceneEditorMain();
Application.Idle += new EventHandler(OnAppIdle);
Application.Run(mMainFrame);
}
static void OnAppIdle(object sender, EventArgs e)
{
while (AppStillIdle)
{
mMainFrame.DoUpdate();
}
}
private static bool AppStillIdle
{
get
{
NativeMethods.Message msg;
return !NativeMethods.PeekMessage(out msg, IntPtr.Zero, 0, 0, 0);
}
}
}
public class NativeMethods
{
/**/
///
Windows Message
[StructLayout(LayoutKind.Sequential)]
public struct Message
{
public IntPtr hWnd;
public uint msg;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
public System.Drawing.Point p;
}
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool PeekMessage(out Message msg, IntPtr hWnd, uint messageFilterMin, uint messageFilterMax, uint flags);
}
}