Any way to create a hidden main window in C#?

前端 未结 12 989
粉色の甜心
粉色の甜心 2020-12-25 13:02

I just want a c# application with a hidden main window that will process and respond to window messages.

I can create a form without showing it, and can then call Ap

12条回答
  •  攒了一身酷
    2020-12-25 13:26

    Using Kami's answer as an inspiration, I created a more complete concept. If you use this solution, don't ever show the hidden window. If you do, the user might close it and then you've lost the ability to control the application exit in an orderly way. This approach can be used to manage a Timer, NotifyIcon, or any other component that is happy living on an invisible form.

    using System;
    using System.Windows.Forms;
    
    namespace SimpleHiddenWinform
    {
        internal class HiddenForm : Form
        {
            private Timer _timer;
            private ApplicationContext _ctx;
    
            public HiddenForm(ApplicationContext ctx)
            {
                _ctx = ctx;
                _timer = new Timer()
                {
                    Interval = 5000, //5 second delay
                    Enabled = true
                };
                _timer.Tick += new EventHandler(_timer_Tick);
            }
    
            void _timer_Tick(object sender, EventArgs e)
            {
                //tell the main message loop to quit
                _ctx.ExitThread();
            }
        }
    
        static class Program
        {
            [STAThread]
            static void Main()
            {
                var ctx = new ApplicationContext();
                var frmHidden = new HiddenForm(ctx);
                //pass the application context, not the form
                Application.Run(ctx);
            }
        }
    }
    

提交回复
热议问题