0

I am doing a console app that I change in start up the width, is it possible to do it before the console launch? right now the console launches at default then changes.

I wish it to launch after the configuration was applied.

using C# in Visual Studio.

Thanks

1 Answers1

0

It is sadly (as far as I can tell) impossible.

At first I thought "Hey, let's hide the window at start, set the size, and show the window again" like so:

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

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

private const int SwHide = 0;
private const int SwShow = 5;


public static void Main()
{
    _consoleHandle = GetConsoleWindow();
    ShowWindow(_consoleHandle, SwHide);

    Console.SetWindowSize(100, 30);

    ShowWindow(_consoleHandle, SwShow);
}

But that didn't work. Even when I tried hiding the console window in a static constructor (so it gets executed before main). And by "didn't work" I mean, the console showed up, vanished, and reappeared with a different size.

Then I stumbled on a Q&A here that said you could hide the console window by setting the output type to "Windows Application" instead of "Console Application". So I thought "hey, I could attach a console after the fact, let's try it":

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

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

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

private const int SwHide = 0;
private const int SwShow = 5;

private const uint AttachParentProcess = 0x0ffffffff;

public static void Main()
{
    AttachConsole(AttachParentProcess);
    var handle = GetConsoleWindow();

    Console.SetWindowSize(100, 30);

    ShowWindow(handle, SwShow);

    Console.WriteLine(Console.WindowHeight);
    Console.WriteLine(Console.WindowWidth);
}

But that didn't work either, for some reason it can't attach a console and it returns an invalid handle meaning I can't do anything.

MindSwipe
  • 7,193
  • 24
  • 47