简体   繁体   English

C#掉落标签(上下移动)

[英]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: 我想做以下事情:使用计时器label2正在倒下,但我想按下空格时标签上升,当我释放它时标签再次下降,直到我再次按空格,我写的像这个,但它一直在下降:

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. 单击设计器中的表单,然后查看“ Properties窗口。 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. 如果KeyDown旁边没有任何内容,则在按下某个键时不会调用Form1_KeyDown方法。 Click the white space and select the method that will be called when the KeyDown event is fired. 单击空格并选择在触发KeyDown事件时将调用的方法。

If there are other controls on the form, you may need to have KeyPreview enabled as well. 如果表单上还有其他控件,您可能还需要启用KeyPreview This tells the form to respond to key presses when another control has focus. 这告诉表单在另一个控件具有焦点时响应按键。

在此输入图像描述

You need to wireup the KeyDown Event properly 您需要正确连接KeyDown事件

Try This: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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