mke*_*yon 15 c# console winforms
我希望从命令行以编程方式运行我的一个Windows窗体应用程序.在准备中,我将自己类中的逻辑与Form分开.现在我陷入困境,试图让应用程序根据命令行参数的来回来回切换.
这是主类的代码:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1) // gets passed its path, by default
{
CommandLineWork(args);
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
private static void CommandLineWork(string[] args)
{
Console.WriteLine("It works!");
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
Form1
我的表单在哪里,It works!
字符串只是实际逻辑的占位符.
现在,当从Visual Studio中运行此命令(使用命令行参数)时,短语It works!
将打印到输出.但是,当运行/bin/Debug/Program.exe文件(或/ Release)时,应用程序崩溃.
我是以正确的方式来做这件事的吗?让我的逻辑类成为由两个独立应用程序加载的DLL会更有意义(即花费更少的开发人员时间)吗?还是有一些我不知道的完全不同的东西?
提前致谢!
Han*_*ant 24
如果检测到命令行参数,则需要P/Invoke AllocConsole().在此主题中检查我的答案以获取所需的代码.AC#样本位于页面下方.在这里重复,因为我不相信那个糟糕的论坛网站:
using System;
using System.Windows.Forms;
namespace WindowsApplication1 {
static class Program {
[STAThread]
static void Main(string[] args) {
if (args.Length > 0) {
// Command line given, display console
AllocConsole();
ConsoleMain(args);
}
else {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
private static void ConsoleMain(string[] args) {
Console.WriteLine("Command line = {0}", Environment.CommandLine);
for (int ix = 0; ix < args.Length; ++ix)
Console.WriteLine("Argument{0} = {1}", ix + 1, args[ix]);
Console.ReadLine();
}
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();
}
}
Run Code Online (Sandbox Code Playgroud)