vb.net 无法 Console.SetWindowPosition

vb.net unable to Console.SetWindowPosition

我正在 VB.NET 中创建一个 Windows 控制台应用程序,但我无法设置相对于屏幕的 window 位置。简而言之,我想要一个将 window 置于屏幕中心的函数。

我尝试使用 Console.SetWindowPosition(w, h) 方法和 Console.WindowTopConsole.WindowLeft 属性。当 returning WindowTopWindowLeft 的值时,它们都是 return 0,如果我尝试使用 Console.WindowLeft = n (n > 0) 更改这些值,程序抛出 OutOfBounds 异常,说明 Window 的大小必须适合控制台的缓冲区。

I 运行 Console.SetWindowSize(80, 35)Console.SetBufferSize(80, 35) 在尝试定位 window 之前,但如果 n 大于 0,它仍然抛出异常。当 returning WindowTopWindowLeft 值时,它们都是 0,即使在 returning 这些值之前移动了控制台 window。

您调用的方法不适用于控制台 window,但适用于控制台 window 显示的字符缓冲区。如果你想移动控制台 window 恐怕你需要使用 Windows API

Imports System.Runtime.InteropServices
Imports System.Drawing
Module Module1

    <DllImport("user32.dll", SetLastError:=True)> _
    Private Function SetWindowPos(ByVal hWnd As IntPtr, _
      ByVal hWndInsertAfter As IntPtr, _
      ByVal X As Integer, _
      ByVal Y As Integer, _
      ByVal cx As Integer, _
      ByVal cy As Integer, _
      ByVal uFlags As UInteger) As Boolean
    End Function

    <DllImport("user32.dll")> _
    Private Function GetSystemMetrics(ByVal smIndex As Integer) As Integer
    End Function

    Sub Main()
        Dim handle As IntPtr = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle
        Center(handle, New System.Drawing.Size(500, 400))
        Console.ReadLine()
    End Sub

    Sub Center(ByVal handle As IntPtr, ByVal sz As System.Drawing.Size)

        Dim SWP_NOZORDER = &H4
        Dim SWP_SHOWWINDOW = &H40
        Dim SM_CXSCREEN = 0
        Dim SM_CYSCREEN = 1

        Dim width = GetSystemMetrics(SM_CXSCREEN)
        Dim height = GetSystemMetrics(SM_CYSCREEN)

        Dim leftPos = (width - sz.Width) / 2
        Dim topPos = (height - sz.Height) / 2

        SetWindowPos(handle, 0, leftPos, topPos, sz.Width, sz.Height, SWP_NOZORDER Or SWP_SHOWWINDOW)
    End Sub

End Module

此代码未考虑第二台显示器的存在