我想在其他表单关闭时取消选中ContextMenuStrip项。 这是我的代码:
Form1中:
public bool ischecked
{
get { return openForm1ToolStripMenuItem.Checked; }
set { openForm1ToolStripMenuItem.Checked = value; }
}
bool isForm2Open = false;
bool isForm3Open = false;
private void openForm1ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!isForm2Open)
{
Form2 frm2 = new Form2();
frm2.Show();
isForm2Open = true;
openForm1ToolStripMenuItem.Checked = true;
}
else
{
openForm1ToolStripMenuItem.Checked = false;
isForm2Open = false;
}
}
窗体2:
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
// Code for Unckeck openForm1ToolStripMenuItem
}
为什么缺乏其他形式的缺血?
答案 0 :(得分:1)
private void openForm1ToolStripMenuItem_Click(object sender, EventArgs e) {
ToolStripMenuItem item = sender as ToolStripMenuItem;
if (!isForm2Open)
{
Form2 frm2 = new Form2();
frm2.FormClosed += (s,ev) => {
item.Checked = false;
isForm2Open = false;
};
frm2.Show();
isForm2Open = true;
openForm1ToolStripMenuItem.Checked = true;
}
else
{
openForm1ToolStripMenuItem.Checked = false;
isForm2Open = false;
}
}
答案 1 :(得分:0)
您可以将表单显示为此对话框
frm2.ShowDialog();
或者你必须在form2中创建一个事件。在表单关闭时触发。您将在表单1中注册该事件,然后取消选中您的框。
在表格2中声明事件,如
public event EventHandler onFormClosed;
然后是Form2的结束事件
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
if(onFormClosed!= null)
onFormClosed(this,EventArgs.Empty);
}
然后以你的形式1
Form2 frm2 = new Form2();
frm.onFormClosed += frm_onFormClosed;
frm2.Show();
这将创建一个像这样的方法
private void frm_onFormClosed(object sender, EventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(() => openForm1ToolStripMenuItem.Checked = false);
}
else
{
openForm1ToolStripMenuItem.Checked = false;
}
}
答案 2 :(得分:0)
您需要引用第二种形式的第一个表单才能更改其属性。此外,上述两个答案是完成此任务的更好方法,即使他们没有直接回答所提出的问题。 :)
Form1中:
public bool ischecked
{
get { return openForm1ToolStripMenuItem.Checked; }
set { openForm1ToolStripMenuItem.Checked = value; }
}
bool isForm2Open = false;
bool isForm3Open = false;
private void openForm1ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!isForm2Open)
{
Form2 frm2 = new Form2();
frm2.MainForm = this;
frm2.Show();
isForm2Open = true;
openForm1ToolStripMenuItem.Checked = true;
}
else
{
openForm1ToolStripMenuItem.Checked = false;
isForm2Open = false;
}
}
窗体2:
public Form MainForm { get; set; }
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
this.MainForm.ischecked = false;
}