Mit anliegendem Beispiel-Code werden dynamisch
In der Auswertung der Menü-Events soll das ContextMenuStrip.SourceControl ermittelt werden.
Das klappt auch bei der ersten Ebene der Menu-Struktur,
warum nicht bei den Subitems?
- eine Picturebox
- sowie eine Textbox generiert und
- jeweil ein Contextmenü erzeugt und zugeordnet.
In der Auswertung der Menü-Events soll das ContextMenuStrip.SourceControl ermittelt werden.
Das klappt auch bei der ersten Ebene der Menu-Struktur,
warum nicht bei den Subitems?
Visual Basic:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim PB As New PictureBox With {.Name = "PB_Test", .BorderStyle = BorderStyle.Fixed3D,
.Size = New Size(100, 150), .Location = New Point(20, 20)}
Me.Controls.Add(PB)
Dim TB As New TextBox With {.Name = "TB_Test", .Text = "testtext", .BorderStyle = BorderStyle.Fixed3D,
.Location = New Point(20, PB.Top + PB.Height + 5)}
Me.Controls.Add(TB)
CMS_events(PB,, {"save", "Rotation|90° links|90° rechts|180°"})
CMS_events(TB,, {"load", "Schrift|bold|italic|understrike"})
End Sub
Private Sub CMS_events(obj As Object, Optional e As EventArgs = Nothing, Optional MTxt As String() = Nothing)
Dim cms As ContextMenuStrip,
Tsmi As ToolStripMenuItem,
aTxt As New List(Of String),
par As Object,
SC As Control,
SCName As String
If TypeOf obj Is Control Then
With CType(obj, Control)
If .ContextMenuStrip Is Nothing Then
cms = New ContextMenuStrip With {.Name = "CMS°"}
For Each itxt In MTxt
aTxt = Split(itxt, "|").ToList
Tsmi = New ToolStripMenuItem(Split(itxt, "|")(0), Nothing, AddressOf CMS_events)
For sx = 1 To aTxt.Count - 1
Tsmi.DropDownItems.Add(sx & " " & aTxt(sx), Nothing, AddressOf CMS_events)
Next
cms.Items.Add(Tsmi)
Next
.ContextMenuStrip = cms
End If
End With
ElseIf TypeOf obj Is ToolStripMenuItem Then
par = obj
Do While TypeOf par IsNot ContextMenuStrip
If TypeOf par.owner Is ContextMenuStrip Then
par = par.owner
SC = CType(par, ContextMenuStrip).SourceControl
Exit Do
ElseIf TypeOf par.owneritem Is ToolStripMenuItem Then
par = par.owneritem
End If
Loop
Try
SCName = SC.Name
Catch ex As Exception
SCName = "Nothing" & vbCrLf & ex.Message & vbCrLf & vbCrLf &
"hier ist das Problem:" & vbCrLf & vbCrLf &
vbTab & "es wird zwar das Contextmenustrip '" & par.name & "'" & vbCrLf &
vbTab & "erkannt, aber '.sourceControl = Nothing'" & vbCrLf & vbCrLf &
"!!! warum ???'"
End Try
MsgBox(TypeName(par) & " = " & par.name & vbCrLf &
TypeName(obj) & " = " & obj.text & vbCrLf & "in SC = " & SCName)
End If
End Sub
End Class