首页 > 解决方案 > 使 keydown 代码只运行一次,在按下开始时

问题描述

我正在编写一段代码,当按下按钮时,它会创建一个图片框,但是当您按住相同的键时,该图片框需要增长。起初我的代码重复了盒子的创建,但现在我尝试了下面的代码,而是创建了一次,但在代码的末尾。有谁知道一些代码如何在第一个被按下的实例上执行部分按键代码,并且只执行一次?

Private Class Form1
      Dim KeyHolding As Boolean = False


Private Sub Btn_1_KeyDown(sender As Object, e As KeyEventArgs) Handles Btn_1.KeyDown
        If Not KeyHolding Then          'the events which are activated once only when the key is pressed
            KeyHolding = True

            Dim PB As New PictureBox With {.Width = Btn_1.Width - 2, .Height = 10, .Top = Btn_1.Top + 20, .Left = Btn_1.Left + 1, .BackColor = Color.Cyan}
            PB.Name = "PB_1"
            TestPanel.Controls.Add(PB)
        Else                            'the events which are constantly done when the key is held

        End If
    End Sub

Private Sub Btn_1_KeyUp(sender As Object, e As KeyEventArgs) Handles Btn_1.KeyUp
        Btn_1.BackColor = SystemColors.Control
        KeyHolding = False
    End Sub

标签: vb.netvisual-studio-codevb.net-2010

解决方案


试试这个

Dim KeyHolding As Boolean = False
Dim PB As PictureBox

Private Sub Btn_1_KeyDown(sender As Object, e As KeyEventArgs) Handles Btn_1.KeyDown
    If Not KeyHolding Then          'the events which are activated once only when the key is pressed
        KeyHolding = True
        PB = New PictureBox With {.Width = Btn_1.Width - 2, .Height = 10, .Top = Btn_1.Top + 20, .Left = Btn_1.Left + 1, .BackColor = Color.Cyan}
        PB.Name = "PB_1"
        TestPanel.Controls.Add(PB)
    Else                            'the events which are constantly done when the key is held
        PB.Width += 10
        PB.Height += 10
    End If
End Sub

Private Sub Btn_1_KeyUp(sender As Object, e As KeyEventArgs) Handles Btn_1.KeyUp
    Btn_1.BackColor = SystemColors.Control
End Sub

推荐阅读