C#演練—Windows應用程式—在windows表單上動態建立操作功能表

來源:互聯網
上載者:User
建立項目和表單
  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呈現對應的狀態。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.