简体   繁体   中英

C# Falling down label (moving up and down)

i want to do the following: with the timer the label2 is falling down, but i want when i press space the label to go up and when i release it the label to go down again until i press the space again, i wrote it like this, but it's keep falling down:

int step = 5;
private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
            case Keys.Space:
                step = -5;
                break;
        }
    }

    private void timer3_Tick(object sender, EventArgs e)
    {
        label2.Location = new Point(label2.Location.X, label2.Location.Y + step);
    }

    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
            case Keys.Space:
                step = 5;
                break;
        }
    }

It sounds like your events are not wired up. Click on the form in the designer, then look at the Properties window. Then click on the lightning bolt, which takes you to the Events pane.

在此输入图像描述

If there's nothing next to KeyDown , the Form1_KeyDown method will not be called when you press a key. Click the white space and select the method that will be called when the KeyDown event is fired.

If there are other controls on the form, you may need to have KeyPreview enabled as well. This tells the form to respond to key presses when another control has focus.

在此输入图像描述

You need to wireup the KeyDown Event properly

Try This:

this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM