Vb.net 还记得上次使用的函数/将函数存储在变量中吗?

Vb.net 还记得上次使用的函数/将函数存储在变量中吗?,vb.net,function,pointers,hotkeys,Vb.net,Function,Pointers,Hotkeys,我有一个程序可以自动化某些过程以节省时间,比如从列表中选择一个随机选项、从列表中选择多个随机选项、将我的社交媒体链接复制到剪贴板等。我为最常用的功能设置了一些全局热键,其余的可以从ContextMenuStrip中选择。显然,右键单击并从ContextMenuStrip中选择一个项目要比按热键花费更长的时间 我想添加一个热键,该热键将执行ContextMenuStrip中最近选择的选项。这样,如果我想连续10次执行某个函数,我可以从ContextMenuStrip中选择它一次,然后只需按热键9次

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


我想添加一个热键,该热键将执行ContextMenuStrip中最近选择的选项。这样,如果我想连续10次执行某个函数,我可以从ContextMenuStrip中选择它一次,然后只需按热键9次就可以了。如何实现这一点?

对于下面的示例,创建一个新的WinForms应用程序项目,并添加一个
文本框
、一个
按钮
上下文列表
。在菜单中添加三个项目,并将其命名为“第一”、“第二”和“第三”。将
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
的三种方法之一。如果单击
按钮
,它将重新执行上一次执行的代码


我还展示了如何在有参数和无参数的情况下执行方法。请注意,在这种情况下,在选择“第二个”菜单项后单击
按钮将执行
Method2
,无论
文本框在第一次执行时包含什么,而不是现在包含什么。如果需要使用当前值,则应该在方法中检索它,而不是将其作为参数传递。我只是包含了这一部分,以便演示如何将参数传递给代理。

这可能需要您进行一些研究,但您可以做的是,不直接调用函数,而是创建一个代理并调用它。委托是一个引用方法的对象,因此您可以将该对象指定给一个变量,然后再访问它。事实上,如果有人没有发布任何代码,我通常不会这样做,但这对您来说可能是完全陌生的,所以我将创建一个示例并将其作为答案发布。