Search code examples
c#dllentry-point

Moving entry point to DLL in a WinForm app


I am trying to figure out a way to pre-process few things before my WinForm app loads. I tried putting static void Main() in a form within a class library project and commented it out from Program.cs. Which generated a compile time error: "...does not contain a static 'Main' method suitable for an entry point". It makes sense since the program is not loaded, the DLL is not loaded either.

So the question is, is there a way to do this at all? I want the form in the DLL to be able to determine which form to launch the application with:

[STAThread]
static void Main()
{
   Application.EnableVisualStyles();
   Application.SetCompatibleTextRenderingDefault(false);

   if(condition1)
   {
      Application.Run(new Form1());
   }
   else if(condition2)
   {
      Application.Run(new Form2());
   }
}

This logic will be used in more than one app so it makes sense to put it in a common component.


Solution

  • Can you just add a static method in your DLL that your application calls instead of doing the processing in main?

    // In DLL
    public static class ApplicationStarter
    {
         public static void Main()
         {
              // Add logic here.
         }
    }
    
    // In program:
    {
         [STAThread]
         public static void Main()
         {
              ApplicationStarter.Main();
         }
    }