效果:选中TextBox或RadioButton时右键点出菜单
*注意要设置TextBox和RadioButton的contextMenu属性值为contextMenu1
private void contextMenu1_Popup(object sender, System.EventArgs e)
{
// Clear the contents of the context menu.
contextMenu1.MenuItems.Clear();
// Add a menu item for the Checked state.
contextMenu1.MenuItems.Add("Checked",new System.EventHandler(this.Checked_OnClick));
// Add a menu item for the Unchecked state.
contextMenu1.MenuItems.Add("Unchecked",new System.EventHandler(this.Unchecked_OnClick));
// Test which control it is.
// If it is the CheckBox, add a menu item for the Indeterminate state.
if (contextMenu1.SourceControl == checkBox1)
{
this.contextMenu1.MenuItems.Add("Indeterminate", new System.EventHandler(this.Indeterminate_OnClick));
}
}
protected void Checked_OnClick(System.Object sender, System.EventArgs e)
{
if (contextMenu1.SourceControl == radioButton1)
radioButton1.Checked = true;
else if (contextMenu1.SourceControl == checkBox1)
checkBox1.Checked = true;
}
protected void Unchecked_OnClick(System.Object sender, System.EventArgs e)
{
if (contextMenu1.SourceControl == radioButton1)
radioButton1.Checked = false;
else if (contextMenu1.SourceControl == checkBox1)
checkBox1.Checked = false;
}
protected void Indeterminate_OnClick(System.Object sender, System.EventArgs e)
{
if (contextMenu1.SourceControl == checkBox1)
checkBox1.CheckState = System.Windows.Forms.CheckState.Indeterminate;
}