C # Close processes minimized to tray, gracefully?

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

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

The application launches CloseMainWindow () when launched in debug mode, when the form is displayed. How can I make the application also listen to CloseMainWindow () without showing it? I do not want the user to be able to interact with the form, if not in debug mode.

I tried several approaches, for example, displaying a window, but setting the size to 0. This shows a small form, that is, not hidden.

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

It is also shown, and then hiding it does not work:

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

Show it, but it is minimized and not shown on the taskbar, it does not work:

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

Am I missing something really obvious here, or is it impossible to close processes minimized to the tray in an elegant way?

+6
source share
2 answers

If I understand the problem correctly, you want to completely hide the form when it is not in debug mode (that is, the window is not visible anywhere except for the task manager), and when someone kills the process through the task manager, you want to execute some code for cleaning or just getting notified.

Based on my decision in 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); } 
+1
source

I'm not sure if you can do this through Process.CloseMainWindow() . Processes without a visible main window, it seems to me, have MainWindowHandle for IntPtr.Zero .

You need some workaround. My advice is to manually monitor the MainWindow Handles:

 static void Main() { ... MainWindow mainWindow = new MainWindow(); [HandleRepository] = mainWindow.Handle; Application.Run(mainWindow); } 

Then, when you want to close the process, do this using a workaround:

 public void EndProcess() { Form mainWindow= (MainWindow)Form.FromHandle([HandleRepository]); mainWindow.Close(); } 

It may not be the most elegant solution, but it should work (did not check it)

0
source

Source: https://habr.com/ru/post/906372/


All Articles