我想要实现一个按钮,当选中时会有一个下拉菜单,当取消选中时,此菜单就会消失。我的问题是,当它或菜单失去焦点时,我无法取消选中该复选框。
复选框的外观模式是按钮。
我的代码:
private void cbSettings_CheckedChanged(object sender, EventArgs e)
{
if (cbSettings.Checked) {cmsSettings.Show(cbSettings, 0, cbSettings.Height);}
else {cmsSettings.Hide();}
}
我试图在contextMenuStrip的VisibleChanged / Closed事件中取消选中复选框,但这导致菜单不隐藏(或隐藏并立即显示)。
答案 0 :(得分:1)
我认为你取消选中上下文菜单关闭事件复选框的方法很好,你需要的是一些“事件取消逻辑”(c),如下所示:
private void OnContextClosing(object sender, EventArgs e)
{
_cancel = true;
cbSettings.Checked = false;
_cancel = false;
}
private void cbSettings_CheckedChanged(object sender, EventArgs e)
{
if(_cancel)
return;
if (cbSettings.Checked) {cmsSettings.Show(cbSettings, 0, cbSettings.Height);}
else {cmsSettings.Hide();}
}
这将使CheckChanged事件无法重新检查您的复选框。
答案 1 :(得分:1)
下面的示例当然不包括交换CheckBox的BackGroundImage以指示CheckState所需的代码。 “连线”的事件应该是显而易见的。希望这有用。
// tested in VS 2010 Pro, .NET 4.0 FrameWork Client Profile
// uses:
// CheckBox named 'checkBox1
// ContextMenuStrip named 'contextMenuStrip1
// TextBox named 'cMenuSelectionInfo for run-time checking of results
// used to position the ContextMenuStrip
private Point cPoint;
// context click ? dubious assumption that 'right' = context click
private bool cmOpenedRight;
// the clicked ToolStripMenuItem
private ToolStripMenuItem tsMIClicked;
private void checkBox1_MouseDown(object sender, MouseEventArgs e)
{
cmOpenedRight = e.Button == MouseButtons.Right;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
// positioning the CheckBox like this
// is something in a 'real-world' example
// you'd want to do in the Form.Load event !
// unless, of course, you'd made the CheckBox movable
if(checkBox1.Checked)
{
contextMenuStrip1.Show();
cPoint = PointToScreen(new Point(checkBox1.Left, checkBox1.Top + checkBox1.Height));
contextMenuStrip1.Location = cPoint;
}
else
{
contextMenuStrip1.Hide();
}
}
private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
// assume you do not have to check for null here ?
tsMIClicked = e.ClickedItem as ToolStripMenuItem;
tbCbMenuSelectionInfo.Text = tsMIClicked + " : " + ! (tsMIClicked.Checked);
}
private void contextMenuStrip1_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
e.Cancel = checkBox1.Checked;
}
private void contextMenuStrip1_Closed(object sender, ToolStripDropDownClosedEventArgs e)
{
if (cmOpenedRight)
{
tbCbMenuSelectionInfo.Text += " : closed because : " + e.CloseReason.ToString();
}
}