How to run a .NET console application in the background

☆樱花仙子☆ 提交于 2019-11-26 04:44:48

问题


I have a console application written in C# that is scheduled to run every 15 minutes or so using the built-in Windows Task Scheduler.

Every time it runs, the black console box pops up for the duration of its execution and then closes. I am not writing anything to the console. Is there a way to make this run in the background?


回答1:


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!




回答2:


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

No more console window.




回答3:


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);



回答4:


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.




回答5:


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.




回答6:


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




回答7:


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.




回答8:


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



来源:https://stackoverflow.com/questions/2686289/how-to-run-a-net-console-application-in-the-background

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