How to run a .NET console application in the background

大城市里の小女人 提交于 2019-11-26 16:07:44
Daniel Dolz

Easy!

It seems hard to believe, but it works as a charm. I have used this for some setup projects, when you want to perform custom tasks with no signs of it.

  • Create the project as a Windows application project (this is the hard part).
  • Never make calls to any form. Just keep on in exactly as in your console application

    class Program
    {
        static void Main(string[] args)
        {
            // Just don't call Application.Run(new frmMain(args));
    
            // ... your code
        }
     }
    

This is because windows application projects are no really different than console, except because of the first form and references. It is totally hidden execution. Try it!

Project > Properties> Application tab > change Output type to "Windows application".

No more console window.

What about implementing the app into a windows service? You can set the interval to 15 mins and run the operation in the timer_tick.

JDMX

You can use the Windows API to minimize the console box. Otherwise you can make it a Windows EXE file that does not actually load a form and call System.Windows.Forms.Application.Run().

Code to minimize the console:

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

public const int SW_SHOWMINIMIZED = 2;

IntPtr winHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
ShowWindow(winHandle, SW_SHOWMINIMIZED);

If you already have a Windows Console app created you can simply change the Output type of your app to Windows Application.

Under your project: Go to Properties > Application Select "Windows Application" as the Output type.

This would be the least impact and you can keep your Windows Task Scheduler running the same task.

If it doesn't write anything to the console you could make it a service. http://msdn.microsoft.com/en-us/library/9k985bc9%28VS.80%29.aspx

It will only show up if it's scheduled to run as the same user that's currently logged in. Create another user on the machine with a ridiculously long password, set it to be an Administrator (only if needed) and schedule the task to run as that user.

This is easy. Set the task to run under an account that is not your login account.

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