Reputation: 1386
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.
Upvotes: 2
Views: 1471
Reputation: 64218
Essentially you are trying to create a custom factory for the form to use for the application. Something like the following:
In the EXE:
static void Main()
{
Application.Run(new Factory.CreateForm());
}
and in your library:
public static class Factory
{
public static Form CreateForm()
{
if( condition ) return new Form1();
else return new Form2();
}
}
Upvotes: 0
Reputation:
static void Main() doesn't make sense in a class library, however your snippet of code should do exactly what you want if placed in Program.cs.
Also, do you need a catch-all 'else' clause, just in case condition1 and condition2 aren't met? May not be required, but in most cases I would expect some form of feedback rather than the application silently exiting - depends on what you are doing of course.
Edit: This might do what you want, if you simply need to separate the logic into a library
// 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;
}
}
Upvotes: 0
Reputation: 564333
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();
}
}
Upvotes: 7
Reputation: 19117
Keep you Main method in Program.cs. Let it call a method in dll which instantiates a Form based on the condition and return it to Main.
Upvotes: 1
Reputation: 34543
The "static void Main" method has to be within the "EXE" assembly, but you could have this method make a call to your shared assembly's version of "Main". You just can't do it directly.
Upvotes: 0