如何从 C# 程序写回命令行
How to write back to command line from c# program
接受 CLI 参数的 Winform 应用程序在 运行 时打开新控制台 window,但我希望它在 CLI 中 运行 而 return 任何 [=18] =]() 在那里
这就是我拆分 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());
}
}
}
"Yo!"出现在新的控制台window,但我想要它出现在命令界面
除了您的代码,您还需要更改以下内容:
1) 在项目设置页面中将您的项目类型设置为 Console Application
。如果未提供命令行参数,您的 WinForms
"mode" 将按预期 运行。
2) 删除对 AllocConsole
.
的调用
3) 隐藏控制台 Window 以防您 运行 使用 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());
}
}
接受 CLI 参数的 Winform 应用程序在 运行 时打开新控制台 window,但我希望它在 CLI 中 运行 而 return 任何 [=18] =]() 在那里
这就是我拆分 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());
}
}
}
"Yo!"出现在新的控制台window,但我想要它出现在命令界面
除了您的代码,您还需要更改以下内容:
1) 在项目设置页面中将您的项目类型设置为 Console Application
。如果未提供命令行参数,您的 WinForms
"mode" 将按预期 运行。
2) 删除对 AllocConsole
.
3) 隐藏控制台 Window 以防您 运行 使用 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());
}
}