菜单条和添加事件的菜单项

时间:2015-11-07 17:27:57

标签: c# winforms

尝试将事件添加到“清除”和“退出”。菜单条和项目显示在表单上,​​不确定如何为清除和退出添加事件。

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();
        }
    }

如果我需要Clear和Exit的事件处理程序,是否需要为每个对象创建一个对象?例如ToolStripMenuItem clearToolStripMenuItem = new ToolStripMenuItem(); ... ToolStripMenuItem exitToolStripMenuItem = new ToolStripMenuItem();

我注意到了一些像

这样的例子
private void clearToolStripMenuItem_Click(object sender, ToolStripItemClickedEventArgs e)

上述内容是否消除了对下面单独的事件处理程序的需求。

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

2 个答案:

答案 0 :(得分:2)

Add method有一个重载,它将EventHandler作为参数

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

答案 1 :(得分:1)

您可以访问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;