因此,我有一個Windows窗體,需要也能夠從控制檯(和靜默)運行。Console.Write正在打印下一個命令提示符
using System;
using System.Windows.Forms;
namespace Clear {
static class Program {
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AttachConsole(int pid);
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();
/// <summary>
/// Main
/// </summary>
/// <param name="args"></param>
[STAThread]
static int Main(string[] args) {
if (args.Length == 0) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new ClearGui());
} else if (args[0].Contains("help")) {
if (!AttachConsole(-1)) { // Attach to an parent process console
AllocConsole(); // Alloc a new console
}
Console.WriteLine("\n\nsyntax: \"" + AppDomain.CurrentDomain.FriendlyName + "\" /s");
} else if (Char.ToLower(args[0][1]).Equals('s')) {
Console.WriteLine(ClearGui());
}
return 0;
}
}
}
的問題是,當你從CMD運行它,你得到的東西是這樣的:
C:\Users\Me>clear.exe help
C:\Users\Me>
syntax: "clear.exe" /s
第二行應該是最後。爲什麼在調用下一個提示後打印到控制檯?
它也有winform的一部分。 – Amorphous 2014-09-03 19:17:00
由於Windows啓動應用程序的方式,這就是導致您提到的問題的原因。避免這種情況的唯一方法是將其設置爲「控制檯應用程序」。這並不妨礙你的應用程序顯示錶單。問題是它總是爲您的應用程序創建一個控制檯窗口,如果顯示窗體,您需要隱藏該窗口。 – wdosanjos 2014-09-03 19:22:47