我有一个像这样的Mainform:
public partial class MainForm : Form
{
string FileName = "";
public MainForm()
{
InitializeComponent();
}
private void goToToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void menuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = (ToolStripMenuItem ) sender;
switch (menuItem.Name.Replace("ToolStripMenuItem",""))
{
case "new":
MenuItemNew();
break;
case "open" :
MenuItemOpen();
break;
case "save":
MenuItemSave();
break;
case "saveAs" :
MenuItemSaveAs();
break;
case "exit" :
MenuItemExit();
break;
case "selectAll" :
MenuItemSelectAll();
break;
}
}
private void MenuItemSelectAll()
{
textBox.SelectAll();
}
private void MenuItemExit()
{
this.Close();
}
private void MenuItemSaveAs()
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text Document |*.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(sfd.FileName);
writer.Write(textBox.Text);
writer.Close();
}
}
private void MenuItemSave()
{
if (FileName == "")
{
MenuItemSaveAs();
}
else
{
StreamWriter writer = new StreamWriter(FileName);
writer.Write(textBox.Text);
writer.Close();
}
}
private void MenuItemOpen()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Text Document|*.txt";
if (ofd.ShowDialog() == DialogResult.OK)
{
FileName = ofd.FileName;
StreamReader reader = new StreamReader(ofd.FileName);
textBox.Text = reader.ReadToEnd();
reader.Close();
}
}
private void MenuItemNew()
{
if (textBox.Text == "")
{
textBox.Text = String.Empty;
}
else
this.Show();
Newform sistema=new Newform();
sistema.ShowDialog();
}
}
像这样的新形式:
public partial class Newform : Form
{
public Newform()
{
InitializeComponent();
}
private void cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void dontsave_click(object sender, EventArgs e)
{
}
private void save_Click(object sender, EventArgs e)
{
this.Hide();
}
}
在我的新表单中点击保存时,我需要在我的主表单中打开MenuItemSaveAs。
答案 0 :(得分:2)
第一
public void MenuItemSaveAs()
然后
private void save_Click(object sender, EventArgs e)
{
this.Hide();
((MainForm)Parent).MenuItemSaveAs()
}
这假设您的表单是MainForm的子代。如果不是那么你需要将对MainForm的引用传递给表单的构造函数并将其保存在本地。 (还有一种方法可以始终找到当前程序的主要形式,但我认为这不是解决问题的优雅方法。)
答案 1 :(得分:1)
如果代码需要操作表单的GUI,则所述代码应该在该表单中。