Search code examples
c#.netcompact-framework

C# Application.Run without Form


Is it possible to call Application.Run, but to not pass a form parameter, or is there an alternative if there’s no form to call?

The Run method doesn’t seem to have any overloads that don’t accept a form.

For example, if I wanted to instantiate a class first, and then have that call the form, is there way to do the equivalent of:

Application.Run(myClass);

Just to clarify, I do still want the functionality that .Run() provides. That is, establish a loop to keep the application running, but instead of tracking a form, track a class or other object.

This is relating to the compact framework initially. I assume that's why the Run method doesn't have the overload I was looking for.


Solution

  • I'm not clear whether you want to do:

    1. You want to load your form somewhere else other than the Main()
    2. Or Run a console or service application with no UI.

    For (1):

    static void main()
    {
        //Your program starts running here<<<
    
        //Do some stuff...
        FormRunner a = new FormRunner();
        a.RunForm();
    
    } // << And ends here
    
    class FormRunner {
    
        public void RunForm() {
            Application.Run(new Form());
        }
    
        //You could call which ever form you want from here?
    } // << And ends here
    

    What you need to know is your program starts from the first line of the main and ends at the last. However, when you call Application.Run(FORM) it loads up a windows message loop for that form. Its a special loop that keeps the program still in the main and waits for events (they're called Windows Messages in win32 API)

    And so the program does not end until the user clicks the close button. When this happens, thats when your program actually will return from its Main.

    (2) So now if you just want a pure console app with no forms:

    static void main()
    {
        AcceptInputs()
        DrawScreen()
    
        //Do something else.
        //Make sure your flow stays within the main
    
    } // << Once you come here you're done.
    
    void AcceptInputs()
    {
        while(true) {
    
            //Keep accepting input
            break; // Call break when you're done. You'll be back in the main
        }
    }
    

    I hope that helped.