C# 表单应用程序中的 Main 方法在哪里?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8992837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where is the Main method in a forms application?
提问by Patryk
I would like to know if there is a way to create GUI program, with main() function (just like in console app), so I'm creating all the objects in main() and I can access/change it from the other functions connected with buttons/textboxes etc. Is it even possible? ;p
我想知道是否有办法使用 main() 函数创建 GUI 程序(就像在控制台应用程序中一样),所以我在 main() 中创建所有对象,我可以从另一个访问/更改它与按钮/文本框等相关的功能。它甚至可能吗?;p
Please understand that I'm very beginner with GUI's, things I'm talking about may be funny but still, i want to learn! Thanks :)
请理解,我是 GUI 的初学者,我所谈论的事情可能很有趣,但我仍然想学习!谢谢 :)
采纳答案by OnResolve
When you create windows form project ( A Gui one), it has a main loop--In fact it requires one. By default, it's in program.cs and it kicks off your form:
当你创建窗体项目(A Gui 一个)时,它有一个主循环——实际上它需要一个。默认情况下,它在 program.cs 中并启动您的表单:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
What you probably want though is the Form constructor. This is in the code behind of the Form (by default Form1.cs) and will look like this:
您可能想要的是 Form 构造函数。这是在表单后面的代码中(默认为 Form1.cs),如下所示:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
回答by Haris Hasan
A WinForm application starts from main
WinForm 应用程序从 main 开始
static void Main()
{
Application.Run(new Form1());
}
Whatever you want to do in mainyou can do it here
无论您想做什么,main都可以在这里完成

