【问题标题】:How to hide current form in Load()如何在 Load() 中隐藏当前表单
【发布时间】:2015-03-26 13:26:03
【问题描述】:

我有一份 EULA 表格,这是要显示的第一个表格。虽然如果用户勾选复选框,我的程序会在同一目录中创建一个隐藏的 txt 文件。如果文件存在,则在程序启动时,我不希望显示 EULA 表单,而是显示主要的 Form1

private void EULA_Load(object sender, EventArgs e)
{
    string path = Path.GetDirectoryName(Application.ExecutablePath);
    string file = path + "EULA.txt";
    if (File.Exists(file))
    {
        this.Hide();
        var form1 = new Form1();
        form1.Closed += (s, args) => this.Close();
        form1.Show();
     }
}

ButtonClick 上,我可以成功使用上述 if 子句中的代码。

上面的代码同时打开了EULAForm1。为什么?

编辑: 我按照建议在Main() 中的Program.cs 中尝试过:

static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        string path = Path.GetDirectoryName(Application.ExecutablePath);
        string file = path + "Mailer_EULA.txt";
        if (File.Exists(file))
        {
            Application.Run(new Form1());
        }
        else
        {
            Application.Run(new EULA());
        }
        AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
    }

但是无论文件是否存在,这都会打开Form1

【问题讨论】:

  • 为什么不在 Program 类中检查static void Main()
  • 因为直到这一刻我才知道这是可能的。 :) 让我检查一下。
  • 如果您在表单的显示事件上添加代码,您将获得所需的结果。但我不认为这是做这件事的正确地方。所以试试 Program 类。
  • 你确定你没有下面的原始Application.Run(new Form1());代码吗?
  • 100% 确定,我复制了整个Main()

标签: c# winforms load


【解决方案1】:

为什么不在 Program 类中检查static void Main()

试试这个:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        string path = Path.GetDirectoryName(Application.ExecutablePath);
        string file = Path.Combine(path, "EULA.txt");
        if (File.Exists(file))
        {
            var form1 = new Form1();
            form1.Closed += (s, args) => this.Close();
            form1.Show();
        }
        else 
        {
            var eula = new EULA();
            eula.Show();
        }
    }
}

【讨论】:

  • thisMain() 中不存在。所以我做了别的事情。请检查我的问题,有更新。
  • 始终使用 Path.Combine(),帮助您避免忘记在文件名前放反斜杠的标准错误。
  • 天啊。我没有在路径和文件名之间放置反斜杠。汉斯·帕桑特是对的。所以我以为我删除了文件,但没有。虽然你解决了我的问题 Tjaart van der Walt,但谢谢。
猜你喜欢
  • 2017-02-07
  • 2014-08-20
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
  • 2019-09-20
  • 2019-04-02
  • 1970-01-01
相关资源
最近更新 更多