VB 控制台应用程序(Console Application)启动时如何在屏幕居中显示
VB 控制台应用程序窗口居中实现方案
原代码失效原因
你之前尝试的代码无法生效有两个核心原因:
Console类没有公开Location属性,该属性是 WinForm 窗体的专属属性,不适用于控制台窗口Console.SetWindowPosition方法的参数是控制台窗口相对于内部文本缓冲区的坐标,作用是控制可见窗口对应缓冲区的显示区域,和屏幕坐标完全无关
实现方案
控制台窗口属于标准的Win32窗口,需要调用Windows系统API实现屏幕位置调整,以下是完整可运行的实现代码:
Imports System.Runtime.InteropServices Imports System.Windows.Forms Module Program ' 导入所需Windows API <DllImport("user32.dll", SetLastError:=True)> Private Function GetWindowRect(hWnd As IntPtr, ByRef lpRect As RECT) As Boolean End Function <DllImport("user32.dll", SetLastError:=True)> Private Function SetWindowPos(hWnd As IntPtr, hWndInsertAfter As IntPtr, X As Integer, Y As Integer, cx As Integer, cy As Integer, uFlags As UInteger) As Boolean End Function <DllImport("kernel32.dll", SetLastError:=True)> Private Function GetConsoleWindow() As IntPtr End Function ' 定义窗口尺寸结构体 Private Structure RECT Public Left As Integer Public Top As Integer Public Right As Integer Public Bottom As Integer End Structure ' SetWindowPos 常量定义 Private Const SWP_NOSIZE As UInteger = &H1 ' 保留窗口尺寸,忽略cx、cy参数 Private Const SWP_NOZORDER As UInteger = &H4 ' 保留窗口层级,忽略hWndInsertAfter参数 Sub Main(args As String()) ' 启动时调用居中方法 CenterConsoleWindow() ' 以下为你的业务逻辑 Console.WriteLine("窗口已居中显示") Console.Read() End Sub ''' <summary> ''' 将控制台窗口居中到主屏幕 ''' </summary> Sub CenterConsoleWindow() ' 获取控制台窗口句柄 Dim hConsoleWnd As IntPtr = GetConsoleWindow() If hConsoleWnd = IntPtr.Zero Then Return ' 读取控制台窗口当前尺寸 Dim windowRect As RECT GetWindowRect(hConsoleWnd, windowRect) Dim windowWidth = windowRect.Right - windowRect.Left Dim windowHeight = windowRect.Bottom - windowRect.Top ' 读取主屏幕工作区尺寸(自动排除任务栏、侧边栏等系统保留区域) Dim workingArea = Screen.PrimaryScreen.WorkingArea Dim centerX = (workingArea.Width - windowWidth) \ 2 Dim centerY = (workingArea.Height - windowHeight) \ 2 ' 应用新的窗口位置 SetWindowPos(hConsoleWnd, IntPtr.Zero, centerX, centerY, 0, 0, SWP_NOSIZE Or SWP_NOZORDER) End Sub End Module
注意事项
- 上述代码用到的
Screen类属于System.Windows.Forms程序集,你需要在项目属性的「引用」设置中添加System.Windows.Forms和System.Drawing的引用才能正常编译 - 如果你不想引入WinForms依赖,可以替换掉
Screen相关逻辑,通过GetSystemMetricsAPI直接读取屏幕尺寸,修改后无需额外引用:' 新增API导入 <DllImport("user32.dll", SetLastError:=True)> Private Function GetSystemMetrics(nIndex As Integer) As Integer End Function Private Const SM_CXSCREEN As Integer = 0 Private Const SM_CYSCREEN As Integer = 1 ' 替换CenterConsoleWindow中的屏幕尺寸读取逻辑 Dim screenWidth = GetSystemMetrics(SM_CXSCREEN) Dim screenHeight = GetSystemMetrics(SM_CYSCREEN) Dim centerX = (screenWidth - windowWidth) \ 2 Dim centerY = (screenHeight - windowHeight) \ 2
内容的提问来源于stack exchange,提问作者user16526006
相关产品推荐
相关产品推荐

