tags:

views:

288

answers:

4

Hi

how I can move any Object on screen in WinForm ?

When I press right -> the object will move right until i'll press any other arrow key

and when I press left <- the object will move left until i'll press any other arrow key

The object all the time will be in motion (like in the Snake game)

thank's in advance

A: 

You need a game loop to continue the direction of the movement you originally initiated with a single press of a button.

Christopher Morley
+1  A: 

You probably want to inherit from Form and override the OnPaint method. You'll probably also need to Invalidate() every time to force repaint. This will set up a simple game loop and allow you to update the screen pretty quickly.

In your OnPaint method you'll update the position of an object based on how much time has elapsed since the last time your OnPaint method was called and which key was pressed last. You'll probably do this by using a velocity as follows:

newPosition = oldPosition + (elapsedTime * velocity)

The value of velocity will change based on which key you press (i.e. negative for left, positive for right). You'll also need a variable and some code to keep track of whether it's moving horizontally or vertically.

This is a pretty low performance way to accomplish this (i.e. it's a hack). If you want to stick with Windows but get better performance without too much work, you might look into XNA. If you want much better performance and are willing to do significantly more work, look into Interop with DirectX and the Win32 API or just switch over all together.

Waylon Flinn
A: 

capture keys, adjust object coordinates.

A: 

Assuming you're doing this in 2D, you could setup an x and y change factor that you setup properly with each arrow key press. Then setup a timer to update position at the rate you want. And when the timer ticks, adjust the position of your object by the x/y change factors.

Timothy Carter