Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reposition console window relative to screen

I'm working on a C# console application and I increased the height of the window using Console.WindowHeight, but now the bottom of the window tends to go off screen when the app is first opened.

Is there way, in a console app, to set the position of the console window relative to the screen? I looked into Console.SetWindowPosition, but this only affects the position of the console window relative to the 'screen buffer,' which doesn't seem to be what I'm after.

Thanks for any help!

like image 459
fyodorfranz Avatar asked Sep 06 '15 00:09

fyodorfranz


1 Answers

Here a solution which uses the window handle and an imported SetWindowPos() native function to achieve what you are looking for:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;


namespace ConsoleWindowPos
{
    static class Imports
    {
        public static IntPtr HWND_BOTTOM = (IntPtr)1;
       // public static IntPtr HWND_NOTOPMOST = (IntPtr)-2;
        public static IntPtr HWND_TOP = (IntPtr)0;
        // public static IntPtr HWND_TOPMOST = (IntPtr)-1;

        public static uint SWP_NOSIZE = 1;
        public static uint SWP_NOZORDER = 4;

        [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
        public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, uint wFlags);
    }

    class Program
    {

        static void Main(string[] args)
        {
            var consoleWnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
            Imports.SetWindowPos(consoleWnd, 0, 0, 0, 0, 0, Imports.SWP_NOSIZE | Imports.SWP_NOZORDER);
            System.Console.ReadLine();
        }
    }
}

The code moves the console window to the top left of your screen, not changing z-order nor changing width/height of the window.

like image 181
BitTickler Avatar answered Oct 26 '22 13:10

BitTickler