如何从c#程序写回命令行
接受CLI参数的Winform应用程序在运行时会打开新的控制台窗口,但我希望它改为在CLI中运行,并返回任何控制台。WriteLine() 这就是我如何拆分GUI和控制台的方法如何从c#程序写回命令行,c#,winforms,command-line-interface,console-application,C#,Winforms,Command Line Interface,Console Application,接受CLI参数的Winform应用程序在运行时会打开新的控制台窗口,但我希望它改为在CLI中运行,并返回任何控制台。WriteLine() 这就是我如何拆分GUI和控制台的方法 static class program{ [STAThread] [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern bool AllocConsole(); static v
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!”出现在新控制台窗口中,但我希望它出现在命令界面中除了您的代码之外,您还需要更改以下内容: 1) 在项目设置页面中将项目类型设置为
控制台应用程序
。如果未提供命令行参数,您的WinForms
“模式”将按预期运行
2) 删除对alloconsole
的调用
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());
}
}
除代码外,您还需要更改以下内容: 1) 在项目设置页面中将项目类型设置为
控制台应用程序
。如果未提供命令行参数,您的WinForms
“模式”将按预期运行
2) 删除对alloconsole
的调用
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());
}
}
这使程序在命令窗口中运行,但现在,当我双击exe和GUI时,控制台窗口会出现,在控制台消失之前,控制台仍会闪烁,但对meThis来说已经足够好了,它让程序在命令窗口中运行,但是现在当我双击exe和GUI时,控制台窗口出现了,在控制台消失之前,它仍然会闪烁,但对我来说已经足够好了