簡體   English   中英

如何找到 ContextMenuStrip 的發送者?

[英]How can I find the sender of ContextMenuStrip?

情況:

我有一個 VB.NET 形式的上下文菜單,在ItemClicked上觸發一個事件處理程序。 自動生成的子程序接收sendere作為參數。 由於我不會多次重新發明輪子,因此我將此上下文菜單鏈接到三個文本框。 讓我們將它們命名為 Textbox1、Textbox2 和 Textbox3。

問題:如何確定菜單是在哪個文本框中打開的?

好的,我已經嘗試了什么?

  • sender包含菜單本身,
  • e.ClickedItem只返回被選中的單個菜單項。
  • sender.Parent總是什么都沒有
  • sender.OwnerItem也總是 Nothing`
  • Me.Textbox1.Focused始終為False ,即使它是菜單的“父”控件。

好的,我找到了一個可以正常工作的解決方案,這里是所有遇到相同問題的 VB.NET 編碼人員的代碼。

上下文菜單鏈接在 TextBox1 中,因此我們需要添加另一個事件處理程序,將發送控件保存到菜單中:

Private Sub TextBox1_MouseUp(sender As Windows.Forms.Control, e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseUp
    If e.Button = Windows.Forms.MouseButtons.Right Then
        ContextMenu.Tag = sender
    End If
End Sub

這是單擊菜單項時事件處理程序的代碼:

Private Sub ContextMenu_ItemClicked(sender As System.Object, e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles ContextMenu.ItemClicked
    ContextMenu.Close()

    If ContextMenu.Tag Is Nothing Then
        Debug.Print("debug info: forgot to set sender? well ... KABOOM!")
        Exit Sub
    End If

    Dim oParent As Windows.Forms.Control
    Try
        oParent = ContextMenu.Tag
    Catch ex As Exception
        Debug.Print("debug info: tag contains data other than sender control. well ... KABOOM!")
        Exit Sub
    End Try

    ' Do fancy stuff here.

    ' Release sender
    ContextMenu.Tag = Nothing
End Sub

ContextMenuStrip有一個SourceControl屬性,其中包含對打開菜單的控件的引用。 該事件從 ContextMenuStrip 中的ToolStripMenuItem之一觸發,因此您必須首先獲取“父級”:

' cast sender to menuitem
Dim mi = CType(sender, ToolStripMenuItem)
' cast mi.Owner to CMS
Dim cms = CType(mi.Owner, ContextMenuStrip)

' the control which opened the menu:
Console.WriteLine(cms.SourceControl.Name)

在某些情況下,SourceControl 可能會丟失,但您可以使用變量和父 ContextMenuStrip Opening 事件自行跟蹤它:

' tracking var:
Private MenuSourceControl As Control
Private Sub cms_Opening(sender As Object, e As CancelEventArgs) Handles cms.Opening
    ' set reference in case/before it is lost
    MenuSourceControl = CType(sender, ContextMenuStrip).SourceControl
End Sub

Private Sub CutToolStripMenuItem_Click(sender...
    If MenuSourceControl IsNot Nothing Then
        ' do your stuff

        ' optionally clear the tracking var
        MenuSourceControl = Nothing
    End If
End Sub

處理子項時獲取SourceControl也應該更容易


您也可以捕捉到相關的控制MouseDown相關的事件Control在情況下,相同的菜單使用不同的控件:

Private Sub lv2_MouseDown(sender As Object, 
         e As MouseEventArgs) Handles lv2.MouseDown,
                  myLV.MouseDown, lv1.MouseDown ...

    If e.Button = Windows.Forms.MouseButtons.Right Then
        MenuSourceControl = DirectCast(sender, Control)
    End If
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM