开发者

How to run a .NET console application in the background

开发者 https://www.devze.com 2022-12-27 13:06 出处:网络
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.

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 ti开发者_高级运维me 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?


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

No more console window.


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!


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消