vb.net unable to Console.SetWindowPosition

旧巷老猫 提交于 2021-02-05 09:56:05

问题


I'm creating a Windows Console application in VB.NET, and I am unable to set the window position relative to the screen. In short, I want a function to centre the window to the screen.

I have tried to use Console.SetWindowPosition(w, h) method and Console.WindowTop, Console.WindowLeft properties. When returning the values for WindowTop and WindowLeft, they both return 0, and if I attempt to change these values with Console.WindowLeft = n (n > 0), the program throws an OutOfBounds exception, stating that the Window's size must fit within the console's buffer.

I run Console.SetWindowSize(80, 35) and Console.SetBufferSize(80, 35) before attempting to position the window, yet it still throws the exception if n is greater than 0. When returning both WindowTop and WindowLeft values, both of them are 0, even if the console window has been moved before returning those values.


回答1:


The methods that you are calling don't work with the Console window, but with the character buffer that is showed by the console window. If you want to move the console window I am afraid that you need to use 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

This code doesn't take in consideration the presence of a second monitor



来源:https://stackoverflow.com/questions/33456055/vb-net-unable-to-console-setwindowposition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!