C#创建右键菜单
范例说明:本范例讲解如何创建右键菜单,重点请注意菜单控件ContextMenuStrip的使用.
关键步骤:
1.创建一个新的Windows工程。
2.把ContextMenuStrip控件拖放到设计界面上,Name属性设置为cmMenu.
3.单击ContextMenuStrip控件的Type Here文本区域,可以输入菜单项的名称,如&new,然后回车.
4.添加RichTextBox控件,设置Name属性为"rchShow".
设置Form和RichTextBox的ContextMenuStript属性为“cmMenu”。
7.双击ContextMenuStrip控件的菜单项,添加Open事件。
/// <summary>
/// 右键菜单Open的处理事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void miOpen_Click(object sender, EventArgs e)
{
OpenFileDialog dlgOpen = new OpenFileDialog();
dlgOpen.Filter = "文本文件(*.txt)|*.txt";
if (dlgOpen.ShowDialog() == DialogResult.OK)
{
this.rchShow.LoadFile(dlgOpen.FileName,RichTextBoxStreamType.PlainText);
}
}
private void Form1_Load(object sender, EventArgs e)
{
ContextMenuStrip cms = new ContextMenuStrip();
cms.Items.Add("第一个");
cms.Items.Add("第二个");
this.ContextMenuStrip = cms;
}
/// 右键菜单Open的处理事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void miOpen_Click(object sender, EventArgs e)
{
OpenFileDialog dlgOpen = new OpenFileDialog();
dlgOpen.Filter = "文本文件(*.txt)|*.txt";
if (dlgOpen.ShowDialog() == DialogResult.OK)
{
this.rchShow.LoadFile(dlgOpen.FileName,RichTextBoxStreamType.PlainText);
}
}
private void Form1_Load(object sender, EventArgs e)
{
ContextMenuStrip cms = new ContextMenuStrip();
cms.Items.Add("第一个");
cms.Items.Add("第二个");
this.ContextMenuStrip = cms;
}