2014-09-03 34 views
0

因此,我有一個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 

第二行應該是最後。爲什麼在調用下一個提示後打印到控制檯?

回答

0

您的應用程序的Output type標記爲Windows Application,但它應該是Console Application。右鍵單擊您的項目並選擇屬性,然後轉到應用程序選項卡。

+0

它也有winform的一部分。 – Amorphous 2014-09-03 19:17:00

+0

由於Windows啓動應用程序的方式,這就是導致您提到的問題的原因。避免這種情況的唯一方法是將其設置爲「控制檯應用程序」。這並不妨礙你的應用程序顯示錶單。問題是它總是爲您的應用程序創建一個控制檯窗口,如果顯示窗體,您需要隱藏該窗口。 – wdosanjos 2014-09-03 19:22:47

0

您創建的是一個靜態的Console Application,可以打開一個Windows Forms Application的實例。但是,您可能會將應用程序的輸出類型設置爲Windows Forms Application而不是正確的Console Application。一旦你改正了輸出類型,這個問題就會消失。

相關問題