vb.net unable to Console.SetWindowPosition

前端 未结 1 1169
一个人的身影
一个人的身影 2021-01-27 13:19

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

相关标签:
1条回答
  • 2021-01-27 13:56

    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

    0 讨论(0)
提交回复
热议问题