Here's a simple game using WinForms
and Timer
, using Graphics
for draw (encapsulates GDI +).
It adds a timer that ticks every 10 milliseconds. Each tick it executes the logic of the game, and then refers to the bitmap image off the screen. This is in contrast to using a continuous loop, as in the example in the link.
The form processes key events separately (unlike the execution of GetKeyState
)
When you resize the form and during the first load, a bitmap image of the return buffer of the desired size is created.
Create a new form and replace all the code below. Control the ball using the arrow keys. There is no concept of death.
using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsGame { public partial class Form1 : Form { Bitmap Backbuffer; const int BallAxisSpeed = 2; Point BallPos = new Point(30, 30); Point BallSpeed = new Point(BallAxisSpeed, BallAxisSpeed); const int BallSize = 50; public Form1() { InitializeComponent(); this.SetStyle( ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer, true); Timer GameTimer = new Timer(); GameTimer.Interval = 10; GameTimer.Tick += new EventHandler(GameTimer_Tick); GameTimer.Start(); this.ResizeEnd += new EventHandler(Form1_CreateBackBuffer); this.Load += new EventHandler(Form1_CreateBackBuffer); this.Paint += new PaintEventHandler(Form1_Paint); this.KeyDown += new KeyEventHandler(Form1_KeyDown); } void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Left) BallSpeed.X = -BallAxisSpeed; else if (e.KeyCode == Keys.Right) BallSpeed.X = BallAxisSpeed; else if (e.KeyCode == Keys.Up) BallSpeed.Y = -BallAxisSpeed;
source share