' Visual Basic
Protected Sub ContextMenu1_Popup(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ContextMenu1.Popup
' Clear the contents of the context menu.
ContextMenu1.MenuItems.Clear()
' Add a menu item for the Checked state.
ContextMenu1.MenuItems.Add("Checked", New System.EventHandler(AddressOf Me.Checked_OnClick))
' Add a menu item for the Unchecked state.
ContextMenu1.MenuItems.Add("Unchecked", New System.EventHandler(AddressOf Me.Unchecked_OnClick))
' Test which control it is.
' If it is the CheckBox, add a menu item for the Indeterminate state.
If ContextMenu1.SourceControl Is CheckBox1 Then
ContextMenu1.MenuItems.Add("Indeterminate", New System.EventHandler(AddressOf Me.Indeterminate_OnClick))
End If
End Sub
为 MenuItem1 创建一个事件处理程序。添加如下代码,检验窗体的 SourceControl 属性,然后根据检验结果设置 RadioButton 或 CheckBox 控件的 Checked 属性:
' Visual Basic
Protected Sub Checked_OnClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
If ContextMenu1.SourceControl Is RadioButton1 Then
RadioButton1.Checked = True
ElseIf ContextMenu1.SourceControl Is CheckBox1 Then
CheckBox1.Checked = True
End If
End Sub
注意 此示例使用 CheckState 属性在 Indeterminate_OnClick 事件处理程序中将 CheckBox 控件设置为 Indeterminate。
有关如何在 Visual Basic 中创建事件处理程序的详细信息,请参见在 Visual Basic 代码编辑器中创建事件处理程序。有关如何在 C# 中创建事件处理程序的详细信息,请参见在 Windows 窗体设计器上创建默认事件处理程序。有关如何在 C++ 中创建事件处理程序的详细信息,请参见 Visual C++ 中的事件处理。
为 MenuItem2 创建类似的事件处理程序。为该事件处理程序输入如下代码:
' Visual Basic
Protected Sub Unchecked_OnClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
If ContextMenu1.SourceControl Is RadioButton1 Then
RadioButton1.Checked = False
ElseIf ContextMenu1.SourceControl Is CheckBox1 Then
CheckBox1.Checked = False
End If
End Sub
为 MenuItem3 创建类似的事件处理程序。为该事件处理程序输入如下代码,确保将事件命名为 Indeterminate_OnClick:
' Visual Basic
Protected Sub Indeterminate_OnClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
If ContextMenu1.SourceControl Is CheckBox1 Then
CheckBox1.CheckState = System.Windows.Forms.CheckState.Indeterminate
End If
End Sub
下面是点击Form3上时动态加载新的Textbox对象,并给他增加extChanged属性。照葫芦画瓢,你可以用在你需要的地方。
Private Sub Form3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Click
Dim t As TextBox
m1Count += 1
t = New TextBox() ’动态生成的Textbox控件
t.Name = "TextBox" & m1Count.ToString
t.Location = New Drawing.Point(0, m1Count * 20)
t.Size = New Drawing.Size(100, 20)
t.Text = "TextBox Control"
Me.Controls.Add(t)
AddHandler t.TextChanged, AddressOf TheHandler '为新控件增加对象事件(内容改变时触发)
End Sub