【问题标题】:How can I toggle button with key VB如何用键 VB 切换按钮
【发布时间】:2019-04-04 11:21:28
【问题描述】:

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

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        toggle = 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

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    您可以使用FormKeyDownKeyUp 事件:

    '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
    

    您还必须启用FormKeyPreview

    Me.KeyPreview = True
    

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


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

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

    但请注意,其他应用程序也可以使用全局或本地热键。

    【讨论】:

    • 我需要添加 Me.KeyPreview = True 到 Form_Load
    • 你可以直接在表单的属性上设置。
    • 它现在可以工作了,谢谢,但是当应用程序在后台时,它就不能工作了,我怎样才能让它在后台工作。
    • stackoverflow.com/questions/5065817/…(但请注意,其他应用程序也可以使用全局或本地热键)。
    • 那是c#?但我需要VB
    【解决方案2】:

    我可能会从其他答案中学习 - 关于 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
    

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

    我希望这会有所帮助 - 但如上所述 - 有更好的方法来实现这一点!

    【讨论】:

      【解决方案3】:

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

      另外,不要使用Button,而是使用Checkbox 并将其Appearance 设置为Button

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-30
        • 2022-11-18
        • 1970-01-01
        • 2012-05-19
        相关资源
        最近更新 更多