How to prevent C # console application from being used as an active window?

Sorry if this was asked, but I can not find the answer to it. Maybe I'm not looking for the right conditions.

I have a console program that should run in the background. The user needs a console so that it remains open white, but it should not become an active window when it starts. They would like to continue what they are working on now, and should not minimize the console every time it starts.

This console application runs several times, each time with a new console window. How can I β€œhide” the console behind the currently running task / window?

+6
source share
2 answers

You can programmatically minimize / restore console windows using the code below:

using System; using System.IO; namespace ConsoleApplication1 { class Class1 { [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); private const int SW_MINIMIZE = 6; private const int SW_MAXIMIZE = 3; private const int SW_RESTORE = 9; [STAThread] static void Main(string[] args) { IntPtr winHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; ShowWindow(winHandle, SW_MINIMIZE); System.Threading.Thread.Sleep(2000); ShowWindow(winHandle, SW_RESTORE); } } } 

If you use Process.Start to launch a console application, it is better to use this:

 System.Diagnostics.ProcessStartInfo process= new System.Diagnostics.ProcessStartInfo(@"MyApplication.exe"); process.WindowStyle=System.Diagnostics.ProcessWindowStyle.Minimized; process.UseShellExecute=false; // Optional System.Diagnostics.Process.Start(process); 
+6
source

I do not know how to prevent the console window from being displayed. The best approach in a console application is to hide the window immediately after loading the application. The visual effect is a quick opening of the console window, after which it disappears. Perhaps this is not optimal.

A better approach might be to use Winexe instead of a console application. Inside a Windows application (possibly a winforms application), never create an instance of the first form. Therefore, nothing is displayed.

This prevents user interaction, but from your description, it looks like what you want.

But I'm not sure that you have control over the "console application".

+1
source

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


All Articles