Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Close processes minimized to tray in a graceful way?

Tags:

c#

I have an application that has can display a window using a Form. The form is only shown if the application is run using a -debug flag, otherwise it is only shown in tray.

var form = new Form();
if(DebugMode)
    form.Show();

The application listens to CloseMainWindow() when run in debug mode, as the form is shown. How can I make the application also listen to CloseMainWindow() without showing it? I don't want the user to be able to interact with the form if not in debug mode.

I've tried several approaches, like displaying the window but setting the size to 0. This shows a small form, i.e. not hidden.

if (!DebugMode)
{
    form.Show();
    form.Size = new Size(0, 0);
}

Also showing it, and then hiding it does not work:

if (!DebugMode)
{
    form.Show();
    form.Hide();
}

Showing it, but started minimized and not shown in taskbar does not work either:

if (!DebugMode)
{
    form.Show();
    form.WindowState = FormWindowState.Minimized;
    form.ShowInTaskbar = false;
}

Am I missing something really obvious here, or is it not possible to close processes minimized to tray in a graceful way?

like image 337
Andreas Avatar asked Jan 19 '12 07:01

Andreas


1 Answers

If i've understood the problem correctly, you want to completely hide the form when not in debug mode (i.e. the window is not seen anywhere but in the task manager) and when someone kills the process via task manager, you want to execute some code for clean-up or just get notified.

Basing my solution on this assumption, the following code should work

 public static bool DebugMode = false;

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

            var form = new Form1();
            form.Load += (s, e) =>
                             {
                                 if (!DebugMode)
                                 {
                                     form.Opacity = 0;
                                     form.ShowInTaskbar = false;
                                 }
                             };

            form.FormClosing += (s, e) =>
                                    {
                                        // Breakpoint hits
                                    };

            Application.Run(form);
        }
like image 162
Raghu Avatar answered Oct 12 '22 19:10

Raghu