Making my console application invisible

▼魔方 西西 提交于 2019-11-30 11:07:36

The best thing to do is just don't compile it as a console application! Compile it as a Windows EXE and no console will show. Then you can just do whatever you need to do in the Main method without showing a UI.

But in any case, if you must hide/show the console window I would steer clear of using FindWindow for this task since there is a much more reliable API for this: GetConsoleWindow. This will give you the HWND of the console window and you can try passing that to ShowWindow.

Searock

As Josh Einstein has suggested you can use ShowWindow Api to hide your window.

Here's a example:

using System.Runtime.InteropServices

class CommandLine
{

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    [DllImport("Kernel32")]
    private static extern IntPtr GetConsoleWindow();

    const int SW_HIDE=0;
    const int SW_SHOW=5;

    static void Main(string[] args)
    {
         IntPtr hwnd;
         hwnd=GetConsoleWindow();
         ShowWindow(hwnd,SW_HIDE);

         //Your logic goes here
    }
}

I am not sure about this code as I have not tested it. Let me know if you face any problem.

Have you tried: Project Properties> Application > output Type: to "Windows Application"?

Its a little more complicated than a console application... but if you want something to truly be running in the background when someone logs in then you could create a Windows Service application.

But it does require a little additional work in setting up and installing the Windows Service but there is an abundance of example code on the web:

http://msdn.microsoft.com/en-us/library/9k985bc9(v=VS.80).aspx

http://msdn.microsoft.com/en-us/library/sd8zc8ha(v=VS.80).aspx

http://www.c-sharpcorner.com/uploadfile/mahesh/window_service11262005045007am/window_service.aspx

http://www.developer.com/net/net/article.php/2173801/Creating-a-Windows-Service-in-NET.htm

http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx

Hello I was creating a Console application to be called by the task scheduler. I didn't want the console app to show up so I changed the project properties to have the output to Windows Application.

Change the output type to Windows application Go to : Project - >Project Properties And change the output type to Windows Application

I tried both methods 2) Searock and then 1) Josh --- with Searock's solution the console app window still appeared, although for a very brief moment --- however with Josh's solution the console did not appear nor did my program have any issues -- of course I did have to replace all the console.writeline calls with a call that logged the information out to a log file

Note: I would have just commented on Josh's solution but I cannot do that quite yet :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!