如何使用VB键切换按钮

时间:2019-04-04 11:21:28

标签: vb.net

我尝试用键切换按钮,但找不到解决方案。有人能帮我吗?这是按钮的代码。

Roll number     New_Sub
  001           Maths,Science,Arts

3 个答案:

答案 0 :(得分:3)

您可以使用Form的{​​{3}}或KeyDown事件:

'bind the KeyUp event
AddHandler Me.KeyUp, AddressOf SubToPressButton

'the Sub which is triggered by the KeyUp event
Sub SubToPressButton(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)

    'click button on key "A"
    If e.KeyCode = Keys.A Then
        Button1.PerformClick()
    End If
End Sub

'your Button1 click event
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    toggle += 1

    If toggle = 1 Then
        Timer1.Start()
        Button1.Text = "Status: ON"
    Else
        Timer1.Stop()
        toggle = 0
        Button1.Text = "Status: OFF"
    End If
End Sub

您还必须启用Form中的KeyUp

Me.KeyPreview = True

您可以将以上行设置为New的构造函数(Load)或Form事件。您也可以直接在KeyPreview的属性上启用Form


您需要在应用程序外部切换按钮吗?

在这种情况下,您需要全局键盘挂钩。您已经可以在StackOverflow上找到解决方案:

但是要小心,其他应用程序也可以使用全局或本地热键。

答案 1 :(得分:0)

我可能会从其他答案中学习到-关于KeyUp / Down事件,但是只是为了增强您现有的代码,请尝试以下方法;

Private toggle As Boolean

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If Not toggle Then
        Timer1.Start()
        Button1.Text = "Status: ON"
    Else
        Timer1.Stop()
        Button1.Text = "Status: OFF"
    End If
    toggle = Not toggle
End Sub

我所做的是;   将切换整数更改为布尔值-因为将其用作标志   使用该标志可在每次单击按钮时打开或关闭计时器   在每个按钮单击结束时将标志反转

我希望能有所帮助-但如上所述,有更好的方法来实现这一目标!

答案 2 :(得分:0)

使用加速键,即在Text属性中添加一个&符号,然后可以将后续字符的键与Alt键一起使用。

此外,使用Button并将其Checkbox设置为Appearance的{​​{1}}。