7

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!

4

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks a lot for the reply! For some reason this isn't working for me yet; i.e. the window is still opening in the middle region of the screen.
Yes but then it should "jump" to the top left. That is what it does for me. Did you set a break point before SetWindowPos(), maybe?
I do that btw. on Windows 7 x64 with VS2015 community edition, Debug| Any CPU build configuration.
So I tried running it with the break point and definitely saw it jump to the top left. Is it possible to make it stay in that position?
Could not get this to work on a system running Windows 10 x64 and Visual Studio 2015 WITHOUT using debug. Thanks for the effort, though.
|
-1

You can use Console.SetWindowPosition(int left, int top), which works for both .NET Framework and .NET 5.0.

1 Comment

This sets the wrong "position" than what was asked - see the original question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.