USLTD
USLTD

Reputation: 309

How to move C# Console Application window to the center of the screen

I'm working with a C# Console Application. How can I move the application window to the center of the screen?

Additional details

Framework version: .NET Core 3.1
Size of the window: 37x20 (Console.SetWindowSize(37, 20);)

Upvotes: 3

Views: 3641

Answers (3)

user27268914
user27268914

Reputation: 11

Cannot comment yet, therefore replying to the main question.

In my implementation, this handle would return IntPtr.Zero:

IntPtr window = Process.GetCurrentProcess().MainWindowHandle;

Since I don't know the reason for it, fixed it by importing and using this method:

[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetConsoleWindow();

...

IntPtr window = GetConsoleWindow();

Upvotes: 0

Geert Jan
Geert Jan

Reputation: 428

I would find the console's classname in all open windows. That is "ConsoleWindowClass". Just to be sure to get a handle on the terminal. In my code Kader1 is the desktop rectangle, Kader2 is the terminal's window rectangle.

using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Center
{
    class Program
    {
        public static user32.RECT Kader1, Kader2;
        public static IntPtr hWnd;
        public static bool bRet;
        static void Main(string[] args)
        {
            Kader1 = new user32.RECT();
            bRet = user32.GetWindowRect(user32.GetDesktopWindow(), out Kader1);
            user32.EnumDelegate filter = delegate (IntPtr hTmp, int lParam)
            {
                StringBuilder strbTitle = new StringBuilder(255);
                int nLength = user32.GetWindowText(hTmp, strbTitle, strbTitle.Capacity + 1);
                string strTitle = strbTitle.ToString();
                StringBuilder strbClass = new StringBuilder(255);
                int cLength = user32.GetClassName(hTmp, strbClass, strbClass.Capacity + 1);
                string strClass = strbClass.ToString();
                if (string.IsNullOrEmpty(strClass) == false && string.IsNullOrEmpty(strTitle) == false && strClass.Contains("IME") == false)
                {
                    if (strClass.Contains("ConsoleWindowClass")) hWnd = hTmp;
                }
                return true;
            };
            Kader2 = new user32.RECT();
            bRet = user32.EnumDesktopWindows(IntPtr.Zero, filter, IntPtr.Zero);
            bRet = user32.GetWindowRect(hWnd, out Kader2);
            bRet = user32.SetWindowPos(hWnd, IntPtr.Zero, Kader1.Right / 2 - (Kader2.Right - Kader2.Left) / 2,
            Kader1.Bottom / 2 - (Kader2.Bottom - Kader2.Top) / 2, Kader2.Right - Kader2.Left, Kader2.Bottom - Kader2.Top, 0x0004);
            if (bRet) Console.WriteLine("Hello Centered Console!");
        }
    }
    class user32
    {
        public delegate bool EnumDelegate(IntPtr hWnd, int lParam);
        [DllImport("user32.dll", EntryPoint = "GetWindowRect",
        ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);
        [DllImport("user32.dll", EntryPoint = "GetDesktopWindow",
        ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
        public static extern IntPtr GetDesktopWindow();
        [DllImport("user32.dll", EntryPoint = "GetWindowText",
        ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpWindowText, int nMaxCount);
        [DllImport("user32.dll", EntryPoint = "GetClassName",
        ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int GetClassName(IntPtr hWnd, StringBuilder lpWindowText, int nMaxCount);
        [DllImport("user32.dll", EntryPoint = "EnumDesktopWindows",
        ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDelegate lpEnumCallbackFunction, IntPtr lParam);
        [DllImport("user32.dll", EntryPoint = "SetWindowPos",
        ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
        public struct RECT
        {
            public int Left, Top, Right, Bottom;
            public RECT(int left, int top, int right, int bottom)
            {
                Left = left;
                Top = top;
                Right = right;
                Bottom = bottom;
            }
        }
    }
}

Upvotes: 0

Quickz
Quickz

Reputation: 1846

Made a small utility class that allows you to center your console window.

Usage example:

WindowUtility.MoveWindowToCenter();

Full source code:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

static class WindowUtility
{
    [DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("user32.dll", SetLastError = true)]
    static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

    const uint SWP_NOSIZE = 0x0001;
    const uint SWP_NOZORDER = 0x0004;

    private static Size GetScreenSize() => new Size(GetSystemMetrics(0), GetSystemMetrics(1));

    private struct Size
    {
        public int Width { get; set; }
        public int Height { get; set; }

        public Size(int width, int height)
        {
            Width = width;
            Height = height;
        }
    }

    [DllImport("User32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
    private static extern int GetSystemMetrics(int nIndex);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool GetWindowRect(HandleRef hWnd, out Rect lpRect);

    [StructLayout(LayoutKind.Sequential)]
    private struct Rect
    {
        public int Left;        // x position of upper-left corner
        public int Top;         // y position of upper-left corner
        public int Right;       // x position of lower-right corner
        public int Bottom;      // y position of lower-right corner
    }

    private static Size GetWindowSize(IntPtr window)
    {
        if (!GetWindowRect(new HandleRef(null, window), out Rect rect))
            throw new Exception("Unable to get window rect!");

        int width = rect.Right - rect.Left;
        int height = rect.Bottom - rect.Top;

        return new Size(width, height);
    }

    public static void MoveWindowToCenter()
    {
        IntPtr window = Process.GetCurrentProcess().MainWindowHandle;

        if (window == IntPtr.Zero)
            throw new Exception("Couldn't find a window to center!");

        Size screenSize = GetScreenSize();
        Size windowSize = GetWindowSize(window);

        int x = (screenSize.Width - windowSize.Width) / 2;
        int y = (screenSize.Height - windowSize.Height) / 2;

        SetWindowPos(window, IntPtr.Zero, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
    }
}

References:

Bunch of StackOverflow posts that helped me put together this solution. https://stackoverflow.com/a/42306412/5946094
https://stackoverflow.com/a/13547659/5946094
https://stackoverflow.com/a/43793468/5946094
https://stackoverflow.com/a/31273557/5946094

Upvotes: 8

Related Questions