C# 应用程序 GUI 和命令行
我目前有一个带有 GUI 的应用程序。
是否可以从命令行使用相同的应用程序(没有 GUI 并使用参数)。
或者我是否必须为命令行工具创建一个单独的 .exe(和应用程序)?
I currently have an application with a GUI.
Would it be possible to use this same application from the commandline (without GUI and with using parameters).
Or do I have to create a separate .exe (and application) for the commandline tool?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Main
函数接受命令行参数。这是一个简短的示例:
如果您的应用程序的结构尚未明确地进行静默处理(如果您的所有逻辑都塞入 WinForm 代码中),您可以 在 ala CharithJ 的答案中破解静默处理。
由OP编辑
很抱歉劫持您的答案梅林。只是想为其他人提供这里的所有信息。
为了能够在 WinForms 应用程序中写入控制台,只需执行以下操作:
Main
function accepts command line parameters.Here's a short example:
If your app isn't already structured to cleanly do silent processing (if all your logic is jammed into your WinForm code), you can hack silent processing in ala CharithJ's answer.
EDIT by OP
Sorry to hijack your answer Merlyn. Just want all the info here for others.
To be able to write to console in a WinForms app just do the following:
在您的program.cs类中,保持Main方法不变,但将
string[] Args
添加到主窗体中。例如...在 mainform.cs 构造函数中
In your program.cs class keep the Main method as it is but add
string[] Args
to the main form. For example...In mainform.cs constructor
我是 C# 编程新手。但我根据 OP 和 Merlyn 的代码提示进行了即兴创作。我在使用他们的代码提示时遇到的问题是,当我通过双击 app.exe 调用 app.exe 或从 CMD 调用它时,参数长度不同。当 app.exe 从 CMD 作为 CLI 运行时,app.exe 本身将成为第一个参数。下面是我的临时代码,无论是在 GUI 中双击 app.exe 还是在 CMD 中使用 CLI,它都能令人满意地工作。
我希望这对某人有帮助。我的解决方案的唯一缺点是当 app.exe 作为 GUI 运行时,它将打开 CMD 作为控制台输出窗口。但这对我的工作来说没问题。
I am new to c# programming. But I improvised the code hints from OP and Merlyn. The issue I faced when using their code hint was that the argument length is different when I call app.exe by double click on app.exe or when I call it from CMD. When app.exe is run as CLI from CMD then app.exe itself becomes the first arguments. Below is my improvised code which works satisfactory both as GUI double click of app.exe and as CLI from CMD.
I hope this helps someone. The only drawback of my solution is when the app.exe is run as GUI, it will open a CMD as console output window. But this is OK for my work.
您可能需要将您的应用程序构建为控制台应用程序,确定您在“操作”上执行的操作(例如单击按钮)到单独的类中,包括一个在没有提供命令行参数时可以显示的表单,并处理事件通过将它们路由到“Action”类中的常用方法。
You may need to structure your Application as a Console Application, identify what you do on "Actions" - like clicking of the button - into separate class, include a form that can be shown if there were no command line arguments supplied, and handle events by routing them to the common methods in your "Action" class.
我认为这是可能的,只需将你的子系统设置为“控制台”,你就会看到一个控制台窗口以及GUI窗口。
但为了接受来自控制台窗口的命令,我想您将必须创建一个额外的线程来执行此操作。
I think it is possible, just set your subsystem to "console", you will see a console window as well as the GUI window.
But in order to accept commands from the console window, I guess you will have to create an extra thread to do it.