簡體   English   中英

菜單欄和添加帶有事件的菜單項

[英]Menu strip and adding menu items with events

嘗試將事件添加到清除並退出。 菜單欄和項目顯示在窗體上,不確定如何添加清除和退出事件。

MenuStrip thisMenuStrip = new MenuStrip();

ToolStripMenuItem thisFileItem = new ToolStripMenuItem("&File");
        thisFileItem.DropDownItems.Add("&Clear");
        thisFileItem.DropDownItems.Add("E&xit");
        thisMenuStrip.Items.Add(thisFileItem);
        this.Controls.Add(thisMenuStrip);
        thisMenuStrip.Name = "menuStrip";
        TabIndex = 0;

private void clearToolStripMenuItem_Click(object sender, EventArgs e) 
    {
        DialogResult clearMessageBox = MessageBox.Show("Do you really want to clear this form?",
            "Reset Application", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

        if (clearMessageBox == DialogResult.Yes)
        {
            thisMessageTextBox.Text = "";
            thisGenrePictureBox.Image = null;
        }
    }

 private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        DialogResult exitMessageBox = MessageBox.Show("Do you really want to terminate this program?",
            "Exit Application", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

        if (exitMessageBox == DialogResult.Yes)
        {
            Application.Exit();
        }
    }

如果需要清除和退出事件處理程序,是否需要為每個對象創建一個對象? 例如:ToolStripMenuItem clearToolStripMenuItem = new ToolStripMenuItem(); ... ToolStripMenuItem exitToolStripMenuItem = new ToolStripMenuItem();

我注意到一些例子

private void clearToolStripMenuItem_Click(object sender, ToolStripItemClickedEventArgs e)

上面是否消除了對像下面這樣的單獨事件處理程序的需要。

thisClearFileItem.Click += new System.EventHandler(clearToolStripMenuItem_Click);

Add方法的重載以EventHandler作為參數

 thisFileItem.DropDownItems.Add("&Clear", null, clearToolStripMenuItem_Click);
 thisFileItem.DropDownItems.Add("E&xit", null,  exitToolStripMenuItem_Click);

您可以訪問DropDownItems屬性的索引器。

thisFileItem.DropDownItems.Add("&Clear");
thisFileItem.DropDownItems.Add("E&xit");

//Assuming 'clear' is the first item, its index would be 0
thisFileItem.DropDownItems[0].Click += clearToolStripMenuItem_Click;

//Assuming 'exit' is the second item, its index would be 1
thisFileItem.DropDownItems[1].Click += exitToolStripMenuItem_Click;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM