C# 启动时隐藏表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/522154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 06:39:11  来源:igfitidea点击:

Hide form at launch

c#winformsformshide

提问by sippa

I have a program which only needs a NotifyIcon to work as intended. So I've been trying to get the main form to hide when the program starts.

我有一个程序只需要一个 NotifyIcon 就能按预期工作。所以我一直试图在程序启动时隐藏主窗体。

In frmMain_Load, I tried both

在 frmMain_Load 中,我都尝试了

this.Hide();
this.Visible = false;

without success.

没有成功。

They work in other methods, like in the NotifyIcon_MouseClick-method, but I want it to hide at Load.

它们在其他方法中工作,例如在 NotifyIcon_MouseClick 方法中,但我希望它在加载时隐藏。

I saw in another question here at SO where Matias suggested this:

我在 SO 的另一个问题中看到,Matias 提出了这个建议:

BeginInvoke(new MethodInvoker(delegate
{
    Hide();
}));

This works, but when I launch the program I can see the form flashing real fast. It's better than nothing, but I wonder if there is any better solution to this.

这有效,但是当我启动程序时,我可以看到表单快速闪烁。总比没有好,但我想知道是否有更好的解决方案。

Thanks.

谢谢。

采纳答案by VBNight

// In Your Program.cs Convert This
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

// To This
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Form1 TheForm = new Form1();
    Application.Run();
}

// Call Application.Exit() From Anywhere To Stop Application.Run() Message Pump and Exit Application

回答by Quintin Robinson

Don't call Show or ShowDialog on your form, you can have your Application.Run target a custom class that then instantiates a form and doesn't show or creates a NotifyIcon instance and handles everything from there.

不要在表单上调用 Show 或 ShowDialog,您可以让 Application.Run 定位一个自定义类,然后实例化一个表单并且不显示或创建 NotifyIcon 实例并从那里处理所有内容。

回答by Pierre Arnaud

There is an easy way, if your program has the default Visual Studio generated Program.cs file:

如果您的程序具有默认的 Visual Studio 生成的 Program.cs 文件,则有一种简单的方法:

[STAThread]
static void Main()
{
    Application.EnableVisualStyles ();
    Application.SetCompatibleTextRenderingDefault (false);
    Application.Run (new MainForm ());
}

the simple fact of calling Runwill, indeed make the form visible. Try doing the following in the properties of your form:

调用这个简单的事实Run确实会使表单可见。尝试在表单的属性中执行以下操作:

  1. Set WindowStateto Minimized
  2. Set ShowInTaskbarto false
  1. 设置WindowStateMinimized
  2. 设置ShowInTaskbarfalse

This should do the trick!

这应该可以解决问题!

回答by masfenix

You can also put this.hide = true in the form_shown event. I believe that event is fired once only and after the load event. You might see alittle flicker though if your form has a lot of controls and/or the computer is slow.

您也可以将 this.hide = true 放在 form_shown 事件中。我相信该事件仅在加载事件之后触发一次。如果您的表单有很多控件和/或计算机速度很慢,您可能会看到一点点闪烁。

回答by David Anderson

If your program doesn't require a form to run, then the best method is to not have a form at all.
Setup your NotifyIcon in the Program code, and enter a loop until you want to exit the program by setting some value, or calling some method.
In this example setting UserExitCalledto true (Program.UserExitCalled = true) will cause the program to quit.

如果您的程序不需要表单来运行,那么最好的方法就是根本没有表单。
在程序代码中设置您的 NotifyIcon,然后进入一个循环,直到您想通过设置某个值或调用某个方法来退出程序。
在此示例中,设置UserExitCalled为 true ( Program.UserExitCalled = true) 将导致程序退出。

Here is a brief example:

下面是一个简单的例子:

static class Program {
    internal static Boolean UserExitCalled;

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

        // Setup your tray icon here

        while (!UserExitCalled) {
            Application.DoEvents(); // Process windows messages
            Thread.Sleep(1);
        }

        return;
    }
}

Here the full program class from one of my system tray applications as a working example.

这里以我的一个系统托盘应用程序中的完整程序类作为工作示例。

// *********************************************************************
// [DCOM Productions .NET]
// [DPDN], [Visual Studio Launcher]
//
//   THIS FILE IS PROVIDED "AS-IS" WITHOUT ANY WARRANTY OF ANY KIND. ANY
//   MODIFICATIONS TO THIS FILE IN ANY WAY ARE YOUR SOLE RESPONSIBILITY.
//
// [Copyright (C) DCOM Productions .NET  All rights reserved.]
// *********************************************************************

namespace VisualStudioLauncher
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;
    using System.Threading;
    using VisualStudioLauncher.Common.Objects;
    using VisualStudioLauncher.Forms;
    using System.Drawing;
    using VisualStudioLauncher.Common.Data;
    using System.IO;

    static class Program
    {
        #region Properties

        private static ProjectLocationList m_ProjectLocationList;
        /// <summary>
        /// Gets or Sets the ProjectsLocationList
        /// </summary>
        public static ProjectLocationList ProjectLocationList
        {
            get
            {
                return m_ProjectLocationList;
            }

            set
            {
                m_ProjectLocationList = value;
            }
        }

        private static ShellProcessList m_ShellProcessList = null;
        /// <summary>
        /// Gets or Sets the ShellProcessList
        /// </summary>
        public static ShellProcessList ShellProcessList
        {
            get
            {
                return m_ShellProcessList;
            }

            set
            {
                m_ShellProcessList = value;
            }
        }

        private static NotifyIcon m_TrayIcon;
        /// <summary>
        /// Gets the programs tray application.
        /// </summary>
        public static NotifyIcon TrayIcon
        {
            get
            {
                return m_TrayIcon;
            }
        }

        private static bool m_UserExitCalled;
        /// <summary>
        /// Gets a value indicating whether the user has called for an Application.Exit
        /// </summary>
        public static bool UserExitCalled
        {
            get
            {
                return m_UserExitCalled;
            }

            set
            {
                m_UserExitCalled = value;
            }
        }

        // TODO: Finish implementation, then use this for real.
        private static ApplicationConfiguration m_ApplicationConfiguration = null;
        /// <summary>
        /// Gets the application configuration
        /// </summary>
        public static ApplicationConfiguration ApplicationConfiguration
        {
            get
            {
                if (m_ApplicationConfiguration == null)
                    m_ApplicationConfiguration = ApplicationConfiguration.LoadConfigSection(@"./settings.config");

                return m_ApplicationConfiguration;
            }
        }


        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                if (args[0].ToLower() == "-rmvptr")
                {
                    for (int i = 1; i < args.Length; i++) {
                        try {
                            if (File.Exists(Application.StartupPath + @"\" + args[i])) {
                                File.Delete(Application.StartupPath + @"\" + args[i]);
                            }
                        }
                        catch { /* this isn't critical, just convenient */ }
                    }
                }
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            SplashForm splashForm = new SplashForm();
            splashForm.Show();

            while (!UserExitCalled)
            {
                Application.DoEvents();
                Thread.Sleep(1);
            }

            if (m_TrayIcon != null)
            {
                m_TrayIcon.Icon = null;
                m_TrayIcon.Visible = false;
                m_TrayIcon.Dispose();

                GC.Collect();
            }
        }

        #region System Tray Management

        public static void SetupTrayIcon()
        {
            m_TrayIcon = new NotifyIcon();
            m_TrayIcon.Text = Resources.UserInterfaceStrings.ApplicationName;
            m_TrayIcon.Visible = false; // This will be set visible when the context menu is generated
            m_TrayIcon.MouseDoubleClick += new MouseEventHandler(m_TrayIcon_MouseDoubleClick);

            if (Orcas.IsInstalled)
            {
                m_TrayIcon.Icon = Orcas.Icon;
            }
            else if (Whidbey.IsInstalled) {
                m_TrayIcon.Icon = Whidbey.Icon;
            }
            else {
                m_TrayIcon.Icon = SystemIcons.Warning;
                m_TrayIcon.Text = "Visual Studio is not installed. VSL cannot run properly.";
            }
        }

        static void m_TrayIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left)
            {
                return;
            }

            SettingsForm settingsForm = new SettingsForm();
            settingsForm.Show();
        }
        #endregion
    }
}

回答by foliolo

I've done it just changing this property: Application.OpenForms["Form1"].Opacity = 0;

我只是改变了这个属性: Application.OpenForms["Form1"].Opacity = 0;