Aller au contenu

Application console

De Banane Atomic

Liens

Code

using System;

namespace MonNS
{
    class MaClasse
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("");
        }
    }
}

Read input

ConsoleKeyInfo keyInfo = Console.ReadKey(true);
if (keyInfo.Key == ConsoleKey.Escape) { }

Masquer la saisie d'un mot de passe

Masquer la fenêtre de la Console

[DllImport("kernel32.dll")]
private static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

private const int SW_HIDE = 0;
private const int SW_SHOW = 5;

var handle = GetConsoleWindow();
ShowWindow(handle, SW_HIDE);

Couleurs

Console.BackgroundColor = ConsoleColor.DarkRed;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("...");
Console.ResetColor();

Using dependency injection in a .Net Core console application

dotnet add package Microsoft.Extensions.DependencyInjection
Program.cs
static void Main(string[] args)
{
    //setup our DI
    var serviceProvider = new ServiceCollection()
        .AddLogging()
        .AddSingleton<IFooService, FooService>()
        .AddSingleton<IBarService, BarService>()
        .BuildServiceProvider();

    //configure console logging
    serviceProvider.GetService<ILoggerFactory>()
                   .AddConsole(LogLevel.Debug);

    var logger = serviceProvider.GetService<ILoggerFactory>()
                                .CreateLogger<Program>();
    logger.LogDebug("Starting application");

    //do the actual work here
    var bar = serviceProvider.GetService<IBarService>();
    bar.DoSomeRealWork();

    logger.LogDebug("All done!");