[英]How to write back to command line from c# program
接受CLI參數的Winform應用程序在運行時會打開新的控制台窗口,但我希望它改為在CLI中運行並返回任何Console.WriteLine()
這就是我拆分GUI和控制台的方式
static class program{
[STAThread]
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();
static void Main(string[] args){
if (args.Length > 0)
{
AllocConsole();
Console.WriteLine("Yo!");
Console.ReadKey();
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new someForm());
}
}
}
“ Y!” 出現在新的控制台窗口中,但我希望它在命令界面中
除了代碼,您還需要更改以下內容:
1)在項目設置頁面中,將項目類型設置為Console Application
。 如果未提供命令行參數,則WinForms
“模式”將按預期運行。
2)刪除對AllocConsole
的呼叫。
3)如果您正在運行WinForms模式,請隱藏控制台窗口。
這是完整的代碼:
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[STAThread]
static void Main(string [] args)
{
if (args.Length > 0)
{
Console.WriteLine("Yo!");
Console.ReadKey();
}
else
{
ShowWindow(GetConsoleWindow(), 0);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.