簡體   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