首页 > 解决方案 > 还记得上次使用的函数/将函数存储在变量中吗?

问题描述

我有一个程序可以自动执行某些过程以节省时间,例如从列表中选择一个随机选项,从列表中选择多个随机选项,将我的社交媒体链接复制到剪贴板等。我为我设置了一些全局热键最常用的函数,其余的可以从 ContextMenuStrip 中选择。显然,右键单击并从 ContextMenuStrip 中选择一个项目要比按下热键花费更长的时间。

我想添加一个热键,它将执行到 ContextMenuStrip 中最近选择的选项。这样,如果我想连续执行 10 次某个功能,我可以从 ContextMenuStrip 中选择一次,然后只需按热键 9 次即可。我怎样才能做到这一点?

标签: vb.netfunctionpointershotkeys

解决方案


对于下面的示例,创建一个新的 WinForms 应用程序项目并添加 a TextBox、 aButtonContextMenuStrip. 将三个项目添加到菜单中,并将它们命名为“First”、“Second”和“Third”。将 分配ContextMenuStrip给表单的ContextMenuStrip属性。

Public Class Form1

    'A delegate referring to the method to be executed.
    Private method As [Delegate]

    'An array of arguments to be passed to the method when executed.
    Private arguments As Object()

    Private Sub FirstToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles FirstToolStripMenuItem.Click
        'Execute Method1 with no arguments.
        method = New Action(AddressOf Method1)
        arguments = Nothing
        ExecuteMethod()
    End Sub

    Private Sub SecondToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SecondToolStripMenuItem.Click
        'Execute Method2 with text from a TextBox as arguments.
        method = New Action(Of String)(AddressOf Method2)
        arguments = {TextBox1.Text}
        ExecuteMethod()
    End Sub

    Private Sub ThirdToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ThirdToolStripMenuItem.Click
        'Execute Method3 with no arguments.
        method = New Action(AddressOf Method3)
        arguments = Nothing
        ExecuteMethod()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        'Execute again the last method executed.
        ExecuteMethod()
    End Sub

    Private Sub ExecuteMethod()
        If method IsNot Nothing Then
            'Invoke the current delegate with the current arguments.
            method.DynamicInvoke(arguments)
        End If
    End Sub

    Private Sub Method1()
        MessageBox.Show("Hello World", "Method1")
    End Sub

    Private Sub Method2(text As String)
        MessageBox.Show(text, "Method2")
    End Sub

    Private Sub Method3()
        MessageBox.Show("Goodbye Cruel World", "Method3")
    End Sub

End Class

您现在可以右键单击表单并选择一个菜单项来执行名为 和 的三个Method1方法Method2之一Method3。如果单击Button,它将重新执行最后执行的那些。

我还展示了如何执行带参数和不带参数的方法。请注意,在这种情况下,Button在选择“第二个”菜单项后单击 将执行第一次执行Method2TextBox包含的内容,而不是现在包含的内容。如果您需要使用当前值,那么您将在方法中检索它,而不是将其作为参数传递。我只是包含了那部分,所以我可以演示向代表传递参数。


推荐阅读