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呈现对应的状态。
posted on 2006-04-18 02:24 patrickwai 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/goodwin/archive/2006/04/18/377744.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值