我有一个快速而肮脏的winforms应用程序, 在Form()类中编写了很多控件逻辑和内部逻辑。
我需要两次打开相同的表单(其中一个表单就像是对另一个表单的引用),我正在寻找另一种快速又肮脏的解决方案。
我程序类中的代码:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
//Can I run Main() form a again as reference to the intial form?
}
}
是的,我知道最佳做法提到我应该与用户控件分开,等等,请不要判断。 感谢您的帮助,谢谢。
答案 0 :(得分:1)
最适合您的方法是在表单上添加Click方法,然后在其中创建表单的新实例并进行显示
private void Form1_Click(object sender, EventArgs e)
{
var frm = new Form1();
frm.Show();
}
现在您可以在表单上的任意位置单击,它将打开它的另一个实例
答案 1 :(得分:1)
实际上,只要主要目的是运行另一个具有相同格式的实例-在这种情况下为Main
。
您可以通过在从Main
文件的Application.Run(...);
方法进行加载之前将其挂接到Program.cs
的实例上来做到这一点,请参见下面的示例代码片段。
public void Main_Load()
{
var newForm = new Main();
newForm.Show();
}
重要的是不要使用ShowDialog();
来阻止第一个表单。
希望我做对了。
答案 2 :(得分:1)
如果您决定使用Nii解决方案,请记住递归,因为这样的解决方案将永远不会结束。 您将需要一些控件来仅显示一种形式,这样可以工作:
static int control = 0;
...
if (control == 0)
{
control = 1;
var newForm = new Main();
newForm.Show();
}
答案 3 :(得分:1)
您需要这样做
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var thread = new Thread(ThreadStart);
thread.TrySetApartmentState(ApartmentState.STA);
thread.Start();
Application.Run(new Form1());
}
private static void ThreadStart()
{
Application.Run(new Form2());
}
}
您还可以从FirstForm的Form.Load
事件开始其他表单。
private void Form1_Load(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
}