我正在尝试编写一个程序,它可以在控制台或GUI模式下工作,具体取决于执行参数。我已经设法编写了以下示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace wfSketchbook
{
static class Program
{
[DllImport("Kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AttachConsole(int processId);
[DllImport("Kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AllocConsole();
[DllImport("Kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeConsole();
private const int ATTACH_PARENT_PROCESS = -1;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
if (args.Length > 0)
{
if (!AttachConsole(ATTACH_PARENT_PROCESS))
AllocConsole();
Console.WriteLine("Welcome to console!");
Console.ReadKey();
FreeConsole();
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
}它通常工作,但是当程序从系统命令行调用时,cmd似乎没有意识到程序在控制台模式下工作并立即退出:
d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>wfSketchbook.exe test
d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>Welcome to console!
d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>我更希望得到以下输出:
d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>wfSketchbook.exe test
Welcome to console!
d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>我如何纠正这个问题?
发布于 2011-08-15 01:48:14
没有任何可靠的方法可以使Windows应用程序成为控制台和GUI。您的程序是一个Windows应用程序-因此Windows会在控制台窗口之外启动您-当您的程序启动时,您并没有连接到控制台窗口。
您可以在项目的属性中将项目输出更改为控制台应用程序。但是这样你就会得到一个控制台窗口。甚至在您运行之前,Windows就可以看到您的应用程序被标记为控制台应用程序并创建控制台。
有关更多信息和一些解决方法的链接,请参阅此blog post。
发布于 2011-08-15 01:51:21
对于这个问题,没有理想的解决方案。如果Cmd.exe可以看到.exe是控制台模式的应用程序,它只会自动等待程序完成。而你的应用程序就不是这样了。一种解决方法是告诉它等待:
start /wait yourapp.exe参数
另一种方法是始终使用AllocConsole()。它的副作用是创建了第二个控制台窗口。将应用程序类型更改为控制台,然后调用FreeConsole()也不太理想,窗口的闪烁非常明显。选择你的毒药。
https://stackoverflow.com/questions/7058491
复制相似问题