public partial class Form1 : Form
{
ContextMenuStrip MyContextMenuStrip = new ContextMenuStrip();
bool CloseClicked = false;
public Form1()
{
InitializeComponent();
// add close item, name it
MyContextMenuStrip.Items.Add("Close");
// add separator
MyContextMenuStrip.Items.Add("-");
// handle MouseDown to no reshow context menu strip
this.MouseDown += new MouseEventHandler(Form1_MouseDown);
// we will add items here
MyContextMenuStrip.Opening += new CancelEventHandler(cms_Opening);
// we will control closing here
MyContextMenuStrip.Closing += new ToolStripDropDownClosingEventHandler(cms_Closing);
// we will stash a flag on what item is clicked here
MyContextMenuStrip.ItemClicked += new ToolStripItemClickedEventHandler(cms_ItemClicked);
}
void cms_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.Text == "Close")
{
CloseClicked = true;
}
}
void cms_Opening(object sender, CancelEventArgs e)
{
// The opening event is automatically cancelled if there are no items to display.
// To dynamically populate a dropdown in the Opening event, make sure to set
// e.Cancel = false. In this case, we always have an item.
//
// Add a timestamped item
MyContextMenuStrip.Items.Add(DateTime.Now.ToString());
// reset flag
CloseClicked = false;
}
void cms_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
e.Cancel = true;
// only close if the close item is chosen
if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked && CloseClicked)
{
e.Cancel = false;
}
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
// show on right click
if (e.Button == MouseButtons.Right)
{
// only if not already showing
if (!MyContextMenuStrip.Visible)
{
// coordinates relative to form
MyContextMenuStrip.Show(this, e.Location);
}
}
}
}