Assume that I have a C# Solution with 3 projects Main, Program1, Program2.
I want to have a "Main form", when I click on button "Program1" the main form will be hidden, Program1 will be showed, and when I close Program1, the Main form will return.
How can I do this?
I tried add Program1 and PRogram2 as Reference to Project Main and code like below in Main, it works for call Program1, but can't handle event Program1.closed() because when I try to reference Main to Program1, it error
---------------------------
Microsoft Visual Studio
---------------------------
A reference to 'Main' could not be added. Adding this project as a reference would cause a circular dependency.
---------------------------
OK
---------------------------
I searched Google and got nothing helpful!
using System;
using System.Windows.Forms;
namespace Switch
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Program1.Form1 pf1 = new Program1.Form1();
pf1.Show();
this.Hide();
}
}
}
Thanks everyone for answers!
After confirmed with customer, they don't strictly need the "mainform" to be hidden, so I came with another easier solution:
1. For the "child form", I use ShowDiaglog()
instead of Show()
private void btnChildForm1_Click(object sender, EventArgs e)
{
var frm = new ChildForm1();
frm.ShowDialog();
}
For the mainform, I use mutex
to force it to be only 1 instance:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
[STAThread]
static void Main()
{
var mutex = new Mutex(true, "MainForm", out var result);
if (!result)
{
MessageBox.Show("Running!");
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
GC.KeepAlive(mutex);
}
}