- 从“工具箱”拖放一个CheckBox和一个RadioBox到窗体上,然后拖放一个contextMenu到窗体上。
- 设置CheckBox和RadioBox的ContextMenu属性都为contextMenu。
- 设置CheckBox的ThreeState属性为True。
添加代码
- 双击contextMenu1为contextMenu1_Popup事件创建默认处理程序。代码如下:
- private void contextMenu1_Popup(object sender, System.EventArgs e)
{
contextMenu1.MenuItems.Clear();
contextMenu1.MenuItems.Add("Checked",new System.EventHandler(this.Checked_OnClick));
contextMenu1.MenuItems.Add("Unchecked",new System.EventHandler(this.Unchecked_OnClick));
if(contextMenu1.SourceControl==checkBox1)
{
this.contextMenu1.MenuItems.Add("indeterminate",new System.EventHandler(this.Indeterminate_OnClick));
}
} - 为上下文菜单添加事件处理程序
- private void Checked_OnClick(System.Object sender,System.EventArgs e)
{
if(contextMenu1.SourceControl==checkBox1)
{
checkBox1.CheckState=System.Windows.Form.CheckState.Checked;
}
if(contextMenu1.SourceControl==radioBox1)
{
radioBox1.Checked==True;
}
}
private void Unhecked_Onclik(System.Object sender,System.EventArgs e)
{
if(contextMenu1.SourceControl==checkBox1)
{
checkBox1.CheckState=False;
}
if(conMenu1.SourceControle==radioBox1)
{
radioBox1.Checked=False;
}
}
private void Indeterminate_OnClick(System.Object sender,System.EventArgs e)
{
if(contextMenu.SourceControl==checkBox1)
{
checkBox.CheckedState=System.Windows.Form.CheckState.Indeterminate;
}
}
测试应用程序
- 按F5运行应用程序,进行检验。
- 单击checkBox1选中它,然后右键单击显示三个上下文菜单:Checked,Unchecked,Indeterminate,单击其中一个checkBox1呈现对应的状态。
- 单击radioBox1,然后右键单击显示两个上下文菜单:Checked,Unckecked,单击一个radioBox1呈现对应的状态。