how can make my app open in the center of the screen? I know how to work with a Form application, but I don't know how to work with a console, because it doesn't work the same way.
Console.Location = New Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
(Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2)
Console.SetWindowPosition(0, 0)
CodePudding user response:
Try this:
Public Shared Sub CenterConsole()
Dim hWin As IntPtr = GetConsoleWindow()
Dim rc As RECT
GetWindowRect(hWin, rc)
Dim scr As Screen = Screen.FromPoint(New Point(rc.left, rc.top))
Dim x As Integer = scr.WorkingArea.Left (scr.WorkingArea.Width - (rc.right - rc.left)) / 2
Dim y As Integer = scr.WorkingArea.Top (scr.WorkingArea.Height - (rc.bottom - rc.top)) / 2
MoveWindow(hWin, x, y, rc.right - rc.left, rc.bottom - rc.top, False)
End Sub
Private Structure RECT
Public left, top, right, bottom As Integer
End Structure
<DllImport("kernel32.dll", SetLastError:=True)>
Private Shared Function GetConsoleWindow() As IntPtr
<DllImport("user32.dll", SetLastError:=True)>
Private Shared Function GetWindowRect(ByVal hWnd As IntPtr, <Out> ByRef rc As RECT) As Boolean
<DllImport("user32.dll", SetLastError:=True)>
Private Shared Function MoveWindow(ByVal hWnd As IntPtr, ByVal x As Integer, ByVal y As Integer, ByVal w As Integer, ByVal h As Integer, ByVal repaint As Boolean) As Boolean
And when you want to center the console window just call the CenterConsole sub like this:
CenterConsole()