【发布时间】:2013-11-26 20:53:28
【问题描述】:
我在 C# 中创建了一个同时使用表单和控制台的应用程序,在 Program.cs 的 Main() 中调用:
[STAThread]
static void Main(string[] args)
{
if (Form1.compile == 0)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
if (Form1.compile == 1)
{
Form1.compile = 0;
int u;
IntPtr ptr = GetForegroundWindow();
GetWindowThreadProcessId(ptr, out u);
Process process = Process.GetProcessById(u);
AllocConsole();
//a lot of code for the command prompt
}
}
启动应用程序时,首先启动Form1。然后当 Form1 关闭时,它才会加载命令提示符和我放入其中的所有代码。
我的问题是,我如何仅通过按下 Form1 中的按钮来运行第二部分(编译 == 1 时)?是否有可能,因为 Main() 函数仅在启动时被调用,而 Application.Start(Program.Main()) 会出错?
按钮:
private void button1_Click(object sender, EventArgs e)
{
this.Close(); // Any way to open the console part without closing the form?
//this.Hide();
compile = 1;
}
注意:我尝试在控制台之后调用打开 Form1,但我也想在按下按钮时更新控制台,这不会发生。
编辑:对于未来的读者,解决方案只是将所有内容放在 mainform(或其他类)而不是 Main() 中,因为它不会自我更新,因此在启动后无法执行任何操作。
【问题讨论】:
-
编译是静态的吗??
-
我从Form1调用编译,所以它是静态的。 Main() 函数根本不会更新,我希望它在我按下 Form1 中的按钮时更新。
-
只需调用 Application.Exit() 就足够了。 this.Close() 是一个非常不错的第二选择,但不清楚为什么它不会导致 Application.Run() 调用完成。
-
@Hans 好的,我最初认为 Application.Exit() 会关闭表单和控制台。
-
Application.Exit() 将导致
Run()完成并关闭所有打开的窗口,因此它应该可以工作。我有一个问题:当你的窗口从应用程序的 GUI 部分关闭时,你为什么不启动控制台?