C#演练—Windows应用程序—在windows窗体上动态创建上下文菜单

创建项目和窗体
  1. 从“工具箱”拖放一个CheckBox和一个RadioBox到窗体上,然后拖放一个contextMenu到窗体上。
  2. 设置CheckBox和RadioBox的ContextMenu属性都为contextMenu。
  3. 设置CheckBox的ThreeState属性为True。

添加代码
  1. 双击contextMenu1为contextMenu1_Popup事件创建默认处理程序。代码如下:
  2. 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));
                }
            }
  3. 为上下文菜单添加事件处理程序
  4. 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;
        }
    }

测试应用程序

  1. 按F5运行应用程序,进行检验。
  2. 单击checkBox1选中它,然后右键单击显示三个上下文菜单:Checked,Unchecked,Indeterminate,单击其中一个checkBox1呈现对应的状态。
  3. 单击radioBox1,然后右键单击显示两个上下文菜单:Checked,Unckecked,单击一个radioBox1呈现对应的状态。
原文地址:https://www.cnblogs.com/goodwin/p/377744.html