dotnet / dotnet/command-line-api

Working with command line options in Windows Forms doesn't output or return result

Open
#1,435 14 comments 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
3.7k
Forks
428
PR merge metrics
No merged PRs in 30d

Description

I have a Windows Forms application which also need to have command line options. When the application is started with command line options, it would not load a gui but execute the function this gui is intended to execute, but I am not able to get any output to the console window. Is this possible to do given it's not a Console app?
```
using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.CommandLine.IO;
using System.Reflection;
using System.Runtime.InteropServices;

namespace Greetings
{
static class Program
{
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool AttachConsole(uint dwProcessId);

[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern bool FreeConsole();

const uint ATTACH_PARENT_PROCESS = 0x0ffffffff;

///
/// The main entry point for the application.
///
[STAThread]
static void Main(string[] args)
{
var cmd = new RootCommand
{
new Argument("name", "Your name."),
new Option(new[] {"--greeting", "-g"}, "The greeting to use.")
{
IsRequired = true
},
}.WithHandler(nameof(PrintGreeting));

cmd.Invoke(args);
}

private static int PrintGreeting(string name, string greeting, IConsole console)
{
if (!AttachConsole(ATTACH_PARENT_PROCESS))
{
AllocConsole();
}

greeting ??= "Hi";
console.Out.WriteLine($"{greeting} {name}!");

FreeConsole();
return 0;
}

private static Command WithHandler(this Command command, string methodName)
{
var method = typeof(Program).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static);
var handler = CommandHandler.Create(method!);
command.Handler = handler;
return command;
}
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.