我想创建一个从PictureBox继承的自定义PictureBox类。
public partial class Custom : PictureBox
{
public Custom()
{
this.Size = new System.Drawing.Size(20, 20);
this.Image = WindowsFormsApplication1.Properties.Resources.icon;
}
private void Custom_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
}
}
}
我还创建了contextMenuStrip,但无法将其发送到我的MouseClick事件。如果我尝试使用
contextMenuStrip1.Show(Cursor.Position);
我得到的错误是contextMenuStrip1在当前上下文中不存在。如何处理这个事件?
答案 0 :(得分:0)
我处理这个问题的方法很简单。首先,我必须创建委托来处理MouseClick事件。
this.MouseClick +=Custom_MouseClick;
然后创建菜单对象并填写所有需要的信息
private void Custom_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
ContextMenuStrip menu = new ContextMenuStrip();
ToolStripMenuItem addItem = new ToolStripMenuItem();
addItem.Name = "AddMenuItem";
addItem.Text = "Add";
menu.Items.Add(addItem);
ToolStripMenuItem editItem = new ToolStripMenuItem();
editItem.Name = "EditMenuItem";
editItem.Text = "Edit";
menu.Items.Add(editItem);
menu.Show(Cursor.Position);
menu.ItemClicked += menu_ItemClicked;
}
}
然后,为了使我的菜单工作,我必须创建另一个委托来处理ItemClicked菜单事件。
void menu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
[code]
}