Place a small console window on the bottom left of your screen?

As the name says, I want to place it in the lower left corner of the screen. Here is the code I have so far:

    Console.WindowWidth = 50
    Console.WindowHeight = 3
    Console.BufferWidth = 50
    Console.BufferHeight = 3
    Console.BackgroundColor = ConsoleColor.Black
    Console.ForegroundColor = ConsoleColor.DarkMagenta
    Console.Title = "My Title"
    Console.WriteLine("")
    Console.Write(" Press any key to close this window ...")

    Console.ReadKey()

      

+3


source to share


2 answers


You can use Console.WindowTop

and Console.WindowWidth

class System.Console

to set the location of the console window.

Here's an example on MSDN

The property BufferHeight

also BufferWidth

gets / sets the number of rows and columns to display.

WindowHeight

and WindowWidth

properties should always be smaller BufferHeight

and BufferWidth

correspondingly.

WindowLeft

should be less BufferWidth - WindowWidth

and WindowTop

should be less BufferHeight - WindowHeight

.



WindowLeft

and WindowTop

refer to the buffer.

To move the actual console window, this article has a good example.

I used the code and code from the CodeProject example. You can set the location and size of the window in one function. You don't need to install Console.WindowHeight

and again Console.WindowWidth

. This is what my class looks like:

class Program
{
    const int SWP_NOZORDER = 0x4;
    const int SWP_NOACTIVATE = 0x10;

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


    [DllImport("user32")]
    static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter,
        int x, int y, int cx, int cy, int flags);

    static void Main(string[] args)
    {
        Console.WindowWidth = 50;
        Console.WindowHeight = 3;
        Console.BufferWidth = 50;
        Console.BufferHeight = 3;
        Console.BackgroundColor = ConsoleColor.Black;
        Console.ForegroundColor = ConsoleColor.DarkMagenta;

        var screen = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
        var width = screen.Width;
        var height = screen.Height;

        SetWindowPosition(100, height - 300, 500, 100);
        Console.Title = "My Title";
        Console.WriteLine("");
        Console.Write(" Press any key to close this window ...");

        Console.ReadKey();
    }


    /// <summary>
    /// Sets the console window location and size in pixels
    /// </summary>
    public static void SetWindowPosition(int x, int y, int width, int height)
    {
        SetWindowPos(Handle, IntPtr.Zero, x, y, width, height, SWP_NOZORDER | SWP_NOACTIVATE);
    }

    public static IntPtr Handle
    {
        get
        {
            //Initialize();
            return GetConsoleWindow();
        }
    }

}

      

+1


source


Note. Despite their names, setting Console.WindowLeft

and Console.WindowTop

class does not change the window position on the screen. System.Console


Instead, they position the visible portion of the window relative to the (potentially larger) window buffer - you cannot use type System.Console

to reposition console windows on the screen - you need to use the Windows API to do this
.


Below is the code for a complete console application that positions its own window in the lower left corner of the screen according to the location of the taskbar .

Note:



  • It should work with multiple monitor settings - positioning a window on the specific monitor (screen, screen) it is displayed on (mostly), but I haven't personally tested it.

  • Only Windows API functions are used through P / Invoke declarations , avoiding the need to reference the assembly WinForms ( System.Windows.Forms

    ), which is usually not required in console applications.

    • You will see that a lot of the code is about P / Invoke signatures (declarations) for interacting with native Windows APIs; they were gratefully adapted from pinvoke.net

    • The actual code in the method Main()

      is short in comparison.

  • If you compile the code below from a Console Application Project in Visual Studio and run the resulting executable from a Console Window cmd.exe

    (Command Prompt), that Console Window should go to the bottom left corner (containing the screen).

    • To test functionality while working in Visual Studio, place a breakpoint on close }

      and, when execution pauses, Alt-Tab to the console window to check its position.

using System;
using System.Runtime.InteropServices; // To enable P/Invoke signatures.

public static class PositionConsoleWindowDemo
{

    // P/Invoke declarations.

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

    [DllImport("user32.dll")]
    static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);

    const int MONITOR_DEFAULTTOPRIMARY = 1;

    [DllImport("user32.dll")]
    static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);

    [StructLayout(LayoutKind.Sequential)]
    struct MONITORINFO
    {
        public uint cbSize;
        public RECT rcMonitor;
        public RECT rcWork;
        public uint dwFlags;
        public static MONITORINFO Default
        {
            get { var inst= new MONITORINFO(); inst.cbSize = (uint)Marshal.SizeOf(inst); return inst; }
        }
    }

    [StructLayout(LayoutKind.Sequential)]
    struct RECT
    {
        public int Left, Top, Right, Bottom;
    }

    [StructLayout(LayoutKind.Sequential)]
    struct POINT
    {
        public int x, y;
    }

    [DllImport("user32.dll", SetLastError = true)]
    static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);

    [DllImport("user32.dll", SetLastError = true)]
    static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);

    const uint SW_RESTORE= 9;

    [StructLayout(LayoutKind.Sequential)]
    struct WINDOWPLACEMENT
    {
        public uint Length;
        public uint Flags;
        public uint ShowCmd;
        public POINT MinPosition;
        public POINT MaxPosition;
        public RECT NormalPosition;
        public static WINDOWPLACEMENT Default
        {
            get
            {
                var instance = new WINDOWPLACEMENT();
                instance.Length = (uint) Marshal.SizeOf(instance);
                return instance;
            }
        }
    }

    public static void Main()
    {
        // Get this console window hWnd (window handle).
        IntPtr hWnd = GetConsoleWindow();

        // Get information about the monitor (display) that the window is (mostly) displayed on.
        // The .rcWork field contains the monitor work area, i.e., the usable space excluding
        // the taskbar (and "application desktop toolbars" - see https://msdn.microsoft.com/en-us/library/windows/desktop/ms724947(v=vs.85).aspx)
        var mi = MONITORINFO.Default;
        GetMonitorInfo(MonitorFromWindow(hWnd, MONITOR_DEFAULTTOPRIMARY), ref mi);

        // Get information about this window current placement.
        var wp = WINDOWPLACEMENT.Default;
        GetWindowPlacement(hWnd, ref wp);

        // Calculate the window new position: lower left corner.
        // !! Inexplicably, on W10, work-area coordinates (0,0) appear to be (7,7) pixels 
        // !! away from the true edge of the screen / taskbar.
        int fudgeOffset = 7;
        wp.NormalPosition = new RECT() {
            Left = -fudgeOffset,
            Top = mi.rcWork.Bottom - (wp.NormalPosition.Bottom - wp.NormalPosition.Top),
            Right = (wp.NormalPosition.Right - wp.NormalPosition.Left),
            Bottom = fudgeOffset + mi.rcWork.Bottom
        };

        // Place the window at the new position.
        SetWindowPlacement(hWnd, ref wp);

    }

}

      

+6


source







All Articles