在 WinForm 应用程序中将入口点移动到 DLL
我正在尝试找出一种在 WinForm 应用程序加载之前预处理一些事情的方法。我尝试将 static void Main() 放入类库项目中的表单中,并从 Program.cs 中将其注释掉。这生成了编译时错误:“...不包含适合入口点的静态‘Main’方法”。这是有道理的,因为程序没有加载,DLL 也没有加载。
所以问题是,有没有办法做到这一点?我希望 DLL 中的表单能够确定使用哪一种表单来启动应用程序:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if(condition1)
{
Application.Run(new Form1());
}
else if(condition2)
{
Application.Run(new Form2());
}
}
此逻辑将在多个应用程序中使用,因此将其放在通用组件中是有意义的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您是否可以只在 DLL 中添加应用程序调用的静态方法,而不是在 main 中进行处理?
Can you just add a static method in your DLL that your application calls instead of doing the processing in main?
将 Main 方法保留在 Program.cs 中。让它调用dll中的一个方法,该方法根据条件实例化一个Form并将其返回给Main。
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.
“static void Main”方法必须位于“EXE”程序集中,但您可以让此方法调用共享程序集的“Main”版本。你只是不能直接这样做。
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.
static void Main() 在类库中没有意义,但是如果放置在 Program.cs 中,您的代码片段应该完全符合您的要求。
另外,您是否需要一个包罗万象的“else”子句,以防条件 1 和条件 2 不满足?可能不是必需的,但在大多数情况下,我希望得到某种形式的反馈,而不是应用程序默默退出 - 当然取决于您在做什么。
编辑:如果您只需要将逻辑分离到库中,这可能会满足您的要求
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
本质上,您正在尝试为应用程序使用的表单创建一个自定义工厂。类似于以下内容:
在 EXE 中:
以及在您的库中:
Essentially you are trying to create a custom factory for the form to use for the application. Something like the following:
In the EXE:
and in your library: