重新定位控制台窗口相对于屏幕

fyo*_*anz 6 c# console-application

我正在使用C#控制台应用程序,并且我使用Console.WindowHeight增加了窗口的高度,但是现在窗口的底部在首次打开应用程序时会偏离屏幕.

在控制台应用程序中,是否有办法设置控制台窗口相对于屏幕的位置?我查看了Console.SetWindowPosition,但这只会影响控制台窗口相对于'屏幕缓冲区'的位置,这似乎不是我所追求的.

谢谢你的帮助!

Bit*_*ler 6

这里有一个解决方案,它使用窗口句柄和导入的SetWindowPos()本机函数来实现您的目标:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

代码将控制台窗口移动到屏幕的左上角,不改变z顺序,也不改变窗口的宽度/高度.