繁体   English   中英

C#表单切换,反之亦然

[英]C# form switch and vice versa

假设我有一个包含 3 个项目 Main、Program1、Program2 的 C# 解决方案。
我想要一个“主窗体”,当我单击“程序 1”按钮时,主窗体将被隐藏,程序 1 将显示,当我关闭程序 1 时,主窗体将返回。
我怎样才能做到这一点? 我尝试将 Program1 和 PROgram2 添加为对 Project Main 的引用,并在 Main 中添加如下代码,它适用于调用 Program1,但无法处理事件 Program1.closed() 因为当我尝试将 Main 引用到 Program1 时,它出错

---------------------------
Microsoft Visual Studio
---------------------------
A reference to 'Main' could not be added. Adding this project as a reference would cause a circular dependency.
---------------------------
OK   
---------------------------

我搜索了谷歌并没有任何帮助!

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(); 
        }
    }
}

我的解决方案 我的主要形式,很简单

正如 zcui93 评论的那样,您可以使用 process 使其工作。 您可以将所有 3 个都放在同一个文件夹中(当您在客户端计算机上部署应用程序时)

using System.Diagnostics;
...
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "process.exe";
process.StartInfo.Arguments = "-n";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
process.WaitForExit();// Waits here for the process to exit.

在 C# 中,您可以使用Process.Exited事件。 当有人从任务管理器杀死应用程序时有人关闭应用程序时,此事件不起作用。

当项目架构不好时,循环依赖会发生。 在你的情况下,我认为问题可能是 program1 或 program2 有 Main 作为参考。 从程序 1 和程序 2 中删除 de Main 引用。 主项目必须有对program1和program2的引用。

谢谢大家的解答!
与客户确认后,他们并不严格需要隐藏“主窗体”,所以我提出了另一个更简单的解决方案:
1.对于“子窗体”,我使用ShowDiaglog()而不是Show()

    private void btnChildForm1_Click(object sender, EventArgs e)
    {
        var frm = new ChildForm1();
        frm.ShowDialog();
    }
  1. 对于主窗体,我使用mutex强制它只有 1 个实例:

     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); } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM