Pee*_*Haa 46 c# user-interface command-line winforms
我目前有一个带GUI的应用程序.
是否可以从命令行使用相同的应用程序(没有GUI和使用参数).
或者我是否必须为命令行工具创建单独的.exe(和应用程序)?
Mer*_*ham 60
Main
函数接受命令行参数.这是一个简短的例子:
[STAThread]
static void Main(string[] args)
{
if(args.Length == 0)
{
Application.Run(new MyMainForm());
}
else
{
// Do command line/silent logic here...
}
}
Run Code Online (Sandbox Code Playgroud)
如果您的应用程序尚未构建为干净地进行静默处理(如果您的所有逻辑都被卡入WinForm代码中),那么您可以在CharicJ的答案中破解静默处理.
由OPIT编辑 抱歉劫持你的答案Merlyn.只想在这里为其他人提供所有信息.
为了能够在WinForms应用程序中写入控制台,只需执行以下操作:
static class Program
{
// defines for commandline output
[DllImport("kernel32.dll")]
static extern bool AttachConsole(int dwProcessId);
private const int ATTACH_PARENT_PROCESS = -1;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
// redirect console output to parent process;
// must be before any calls to Console.WriteLine()
AttachConsole(ATTACH_PARENT_PROCESS);
if (args.Length > 0)
{
Console.WriteLine("Yay! I have just created a commandline tool.");
// sending the enter key is not really needed, but otherwise the user thinks the app is still running by looking at the commandline. The enter key takes care of displaying the prompt again.
System.Windows.Forms.SendKeys.SendWait("{ENTER}");
Application.Exit();
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new QrCodeSampleApp());
}
}
}
Run Code Online (Sandbox Code Playgroud)
Cha*_*thJ 10
在program.cs类中保持Main方法不变,但添加string[] Args
到主窗体.例如...
[STAThread]
static void Main(string[] Args)
{
....
Application.Run(new mainform(Args));
}
Run Code Online (Sandbox Code Playgroud)
在mainform.cs构造函数中
public mainform(string[] Args)
{
InitializeComponent();
if (Args.Length > 0)
{
// Do what you want to do as command line application.
// You can hide the form and do processing silently.
// Remember to close the form after processing.
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
34790 次 |
最近记录: |