Trapping keystrokes with Form1_KeyDown(...)

178 views Asked by At

I'm trying to make a form move left or right denoted by a primary keystroke by a number of pixels denoted by a secondary keystroke but so far I've not been able to do anything. As far as I can tell I should have no problem here. I have set KeyPreview to true as well.

private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    {
        this.Close();
        int movement = 0;
        if (e.KeyCode == Keys.R)
            lastEntered = 'r';
        else if (e.KeyCode == Keys.L)
            lastEntered = 'l';
        else
        {
            if (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)
            {
                movement = (int)(e.KeyCode - Keys.NumPad0);
                Console.WriteLine(movement);
                this.Left += movement;
            }
            if (lastEntered == 'r')
                this.Left += movement;
            else if (lastEntered == 'l')
                this.Left -= movement;
        }
    }
1

There are 1 answers

2
nawfal On

There are a few things you should change. Take off this.Close from the keydown event first of all. Rest will be clear from the code.

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.R)
        lastEntered = 'r'; //move to an enum preferably 
    else if (e.KeyCode == Keys.L)
        lastEntered = 'l'; //move to an enum preferably 
    else
    {
        if (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)
        {
            int movement = (int)(e.KeyCode - Keys.NumPad0);

            if (lastEntered == 'r')
                this.Left += movement;
            else if (lastEntered == 'l')
                this.Left -= movement;
        }
    }
}

This is when I assume that the last pressed R or L should be remembered always and any other key down doesn't overwrite the lastEntered key which I believe is not what you would be looking into. Modify your code like this to make sense:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.R)
        lastEntered = 'r'; //move to an enum preferably 
    else if (e.KeyCode == Keys.L)
        lastEntered = 'l'; //move to an enum preferably 
    else
    {
        lastEntered = 'u'; //u for unwanted - only if even num keys should overwrite
        if (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)
        {
            int movement = (int)(e.KeyCode - Keys.NumPad0);

            if (lastEntered == 'r')
                this.Left += movement;
            else if (lastEntered == 'l')
                this.Left -= movement;
        }
        //else                   //so that num keys dont overwrite and hence you
        //    lastEntered = 'u'; //could keep pressing num keys to move the form
    }
}