8

我使用ContextMenuStrip爲多個控件,我試圖找出最好的方式來獲得實際上點擊打開上下文菜單的控件。發件人只是給出ToolStripMenuItem引用,該引用具有引用ContextMenuStrip的所有者屬性,但我無法弄清楚如何判斷點擊來自哪個控件。必須有一個簡單的方法來檢查這個,對嗎?我在ToolStripMenuItem的點擊事件中檢查它。如何獲得單擊的控件以打開ContextMenuStrip?

Friend WithEvents mnuWebCopy As System.Windows.Forms.ToolStripMenuItem 
... 
Private Sub mnuWebCopy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuWebCopy.Click 

我發現了一個similar post這一點,但提到使用SourceControl性質,我看不到這裏。

我正在使用Visual Studio 2008,VB.Net winforms。

回答

20
Private Sub mnuWebCopy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuWebCopy.Click 

Dim myItem As ToolStripMenuItem = CType(sender, ToolStripMenuItem) 
Dim cms As ContextMenuStrip = CType(myItem.Owner, ContextMenuStrip) 

MessageBox.Show(cms.SourceControl.Name) 

End Sub 
+0

謝謝,那正是我所錯過的。 – 2010-01-15 22:11:40

6

您的發件人是ToolStripMenuItem - 投它。
它的主人是一個ContextMenuStrip - 得到它。

SourceControl是ContextMenuStrip上的一個屬性,並引用了顯示ContextMenuStrip的最後一個控件。

+0

甜和對點! – HumbleBeginnings 2017-06-23 19:35:01

0
Private Sub kdgToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles kdgToolStripMenuItem.Click 
    Dim sms = (sender.GetCurrentParent()).SourceControl.name 
    MsgBox(sms) 
End Sub 

「///更快

-1

在VB.NET 2013年這一工作,所以罰款:

Dim cms As ContextMenuStrip = CType(sender, ContextMenuStrip) 
MessageBox.Show(cms.SourceControl.Name) 
0
Private Sub cmsRightClick_Click(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles cmsRightClick.MouseClick 
    Dim s As String = CType(sender, ContextMenuStrip).GetItemAt(CType(sender, ContextMenuStrip).DisplayRectangle.X, _ 
    CType(sender, ContextMenuStrip).DisplayRectangle.Y + e.Y).Text.Trim() 


    MsgBox(s) 
    Select Case s 
     Case Is = "Select Summary Total" 
      Dim x = 0 
     Case Is = "Select Collections" 
      Dim x = 1 
     Case Is = "UnSelect" 
      Dim x = 2 
     Case Is = "Reconcile" 
      Dim x = 3 
     Case Is = "Undo Reconciliation" 
      Dim x = 4 
    End Select 
End Sub 
相關問題