   Keypress and Keydelay in c#
  I've taken some free tetris sourcecode I found on the net and am looking to improve it to mimic a game I play online.The major problem I have is the code uses the keypress event, which is controlled by the windows environment. When I press an arrow key, I want to define in my code how long it should wait before executing one action, and then executing the same action repeatedly, and also define how long it should wait between the repeated actions.What I want to know is the best way to implement a user definable key delay and key repeat in my program. I imagine it would involve using timers, but I can't get my head around the concept enough.I'd be greatful for anything from a useful URL to reference to actual sourcecode I would be able to modify to suit my needs.Thanks heaps!Steve   
  well the other approach is to detect when the key is down and store that state, and alter that state when it's released.  Every frame when moving stuff around you can detect what states the keys you are interested in and act accordingly   ;  I made a quick hacky solution and zipped the project together to a compilable sample (VC#2005EE):RepeatedKeys.zip (14 KB).Here's the relevant code. The "player" is a disabled button, and the gameloop is simulated with a Timer. You probably want to modify this a bit, but I hope the concept is brung forward:public partial class Form1 : Form{public Form1(){InitializeComponent();timerGameLoop.Interval = FrameTime;}private void Form1_KeyDown(object sender, KeyEventArgs e){if ((int)e.KeyCode < 256) {keysDown[(int)e.KeyCode] = true;HandleKey(e.KeyCode);timeToAction[(int)e.KeyCode] = FirstRepeatTime;}}private void Form1_KeyUp(object sender, KeyEventArgs e){if ((int)e.KeyCode < 256) {keysDown[(int)e.KeyCode] = false;}}private void HandleKey(Keys key){switch (key) {case Keys.Up:buttonPlayer.Top -= PlayerStepSize;break;case Keys.Down:buttonPlayer.Top += PlayerStepSize;break;case Keys.Left:buttonPlayer.Left -= PlayerStepSize;break;case Keys.Right:buttonPlayer.Left += PlayerStepSize;break;}}private const int FrameTime = 10;private const int FirstRepeatTime = 300;private const int LaterRepeatTime = 100;private const int PlayerStepSize = 5;private bool[] keysDown = new bool[256];private int[] timeToAction = new int[256];private void timerGameLoop_Tick(object sender, EventArgs e){for (int i = 0; i < 256; i++) {if (keysDown) {timeToAction -= FrameTime;if (timeToAction <= 0) {HandleKey((Keys)i);timeToAction = LaterRepeatTime;}}}}}If you have any troubles or questions (for instance is unable to compile) let me know.[Edited by - Enselic on June 3, 2006 4:55:22 AM];Quote:Original post by EnselicI made a quick hacky solution and zipped the project together to a compilable sampleThanks heaps mate! I'll have to hack it a bit to see if i can integrate it with the code i already have, but it looks perfect.Will let you know how i go.Steve