Moving an entry point to a DLL in a WinForm application

I am trying to figure out a way to pre-process several things before loading a WinForm application. I tried to put a static void Main () on the form inside the class library project and commented on this from Program.cs. Which generated a compile-time error: "... does not contain a static" Basic "method suitable for an entry point." This makes sense, since the program is not loaded, the DLL also does not load.

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 run 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 several applications, so it makes sense to include it in a common component.

+3
5

DLL, ?

// In DLL
public static class ApplicationStarter
{
     public static void Main()
     {
          // Add logic here.
     }
}

// In program:
{
     [STAThread]
     public static void Main()
     {
          ApplicationStarter.Main();
     }
}
+7

Program.cs. dll, Main.

+1

"static void Main" "EXE", "Main". .

0

static void Main() , , , Program.cs.

, catch-all 'else', , 1 2 ? , , , , , , .

: , ,

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

    if(MyLib.Condition1)
    {
        Application.Run(new Form1());
    }
    else if(MyLib.Condition2)
    {
        Application.Run(new Form2());
   }
}


// MyLib.cs
...
public static bool Condition1
{
    get
    {
         return resultOfLogicForCondition1;
    }
}
public static bool Condition2
{
    get
    {
         return resultOfLogicForCondition2;
    }
}
0

, factory , . - :

EXE:

static void Main()
{
    Application.Run(new Factory.CreateForm());
}

:

public static class Factory 
{
    public static Form CreateForm()
    {
        if( condition ) return new Form1();
        else return new Form2();
    }
}
0

Source: https://habr.com/ru/post/1716513/


All Articles