我有一个程序可以自动执行某些过程以节省时间,例如从列表中选择随机选择,从列表中选择多个随机选择,将社交媒体链接复制到剪贴板等。我设置了一些全局选项。我最常用功能的热键,其余的可以从ContextMenuStrip中选择。显然,右键单击并从ContextMenuStrip中选择一个项目要比按热键花费更长的时间。
我想添加一个热键,它将对ContextMenuStrip中最近选择的选项执行。这样,如果我想连续执行某项功能10次,则可以从ContextMenuStrip 中选择它,然后只需简单地按9次热键即可。我该如何实现?
答案 0 :(得分:1)
对于下面的示例,创建一个新的WinForms应用程序项目,并添加一个TextBox
,一个Button
和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
,而不是它所执行的操作。现在包含。如果需要使用当前值,则可以在方法内部检索它,而不是将其作为参数传递。我只是包括了那一部分,所以我可以向参会者演示传递参数。