vb.net - 还记得上次使用的函数/将函数存储在变量中吗?
问题描述
我有一个程序可以自动执行某些过程以节省时间,例如从列表中选择一个随机选项,从列表中选择多个随机选项,将我的社交媒体链接复制到剪贴板等。我为我设置了一些全局热键最常用的函数,其余的可以从 ContextMenuStrip 中选择。显然,右键单击并从 ContextMenuStrip 中选择一个项目要比按下热键花费更长的时间。
我想添加一个热键,它将执行到 ContextMenuStrip 中最近选择的选项。这样,如果我想连续执行 10 次某个功能,我可以从 ContextMenuStrip 中选择一次,然后只需按热键 9 次即可。我怎样才能做到这一点?
解决方案
对于下面的示例,创建一个新的 WinForms 应用程序项目并添加 a TextBox
、 aButton
和ContextMenuStrip
. 将三个项目添加到菜单中,并将它们命名为“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
在选择“第二个”菜单项后单击 将执行第一次执行Method2
时TextBox
包含的内容,而不是现在包含的内容。如果您需要使用当前值,那么您将在方法中检索它,而不是将其作为参数传递。我只是包含了那部分,所以我可以演示向代表传递参数。
推荐阅读
- java - 从json字符串反序列化字节数组
- javascript - 在 Google Sheets 脚本编辑器上创建嵌套 For-Loop 以将数据自动提取为所需格式
- path - 如何修改 Torch Hub 模型的下载路径
- laravel - laravel 6 上的 npm run watch 有很多警告和错误
- docker-compose - docker-compose 给出错误“无法访问该文件,因为它正在被另一个进程使用”。与 docker vanilla 不一样
- java - 使用带有 XSSF 和 SAX 的 poi 在 JAVA 中实现内存高效的 XLSX 阅读器,但不知道如何获取公式?
- django - django-storages EndpointConnectionError
- java - Spring Data JPA save() 返回实体
- apache-spark - SPARK Application + HDFS + User Airflow 不是 inode=alapati 的所有者
- c# - 如何使用 Caliburn Micro 检测窗口关闭方法