开发者

How to make my program a background process

开发者 https://www.devze.com 2022-12-18 19:48 出处:网络
I wrote a program in C# .NET, that needs to be run in the background. I mean it should have any user interface. Neither a GUI nor a CLI. It is not also awindows service(because it must run only after

I wrote a program in C# .NET, that needs to be run in the background. I mean it should have any user interface. Neither a GUI nor a CLI. It is not also a windows service(because it must run only after user has logged in).

It should just run in background. example of such programs are AdobeUpdater.exe , GoogleUpdater.exe 开发者_运维问答etc.


Another option would be to create a Windows Application and set these two properties:

        this.WindowState = FormWindowState.Minimized;
        this.ShowInTaskbar = false;


You can create a Console application, and then change it's properties in the project settings to a Windows application (rather than console). Or you can create a Windows Forms application that ddoesn't actually create any forms.


I often use the following solution for this case: create an application context and use that in the WinForm's project instead of a form.

  1. Create an applicationcontext class

    public class MyApplicationContext : ApplicationContext
    {
            public MyApplicationContext()
            {
            }
    
            void Exit(object sender, EventArgs e)
            {
                    Application.Exit();
            }
    }
    
  2. In Program.cs -> replace original Application.Run() call

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
    
        Form1 frm = new Form1(); //remove if not needed 
        Application.Run(new MyApplicationContext());
    }
    
  3. Because you don't show the form anymore, you need to provide other ways to close the application. I.e. use system tray and then call:

    Application.Exit();
    

Note: Using the above (without ever showing the form), you will never get the usual form events like load, closing, closed.


Use Task Scheduler to run it on a schedule (which can be based on when user logs in). Or add it to the registry to run on startup.

HKLM\Software\Microsoft\Windows\CurrentVersion\Run


You might reconsider using a Windows service and having it monitor for logon/logoff events using the System.Management.ManagementEventWatcher class. This gives an example of a logoff event watcher: http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/0c1bded8-0cce-4260-bd28-4b4ffce0d27d.

0

精彩评论

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

关注公众号