由于在VB.NET中定位表单的内置功能并不总是适合使用我尝试让我的sub做到这一点.
但我错过了一些东西……
Public Sub form_center(ByVal frm As Form,Optional ByVal parent As Form = Nothing) Dim x As Integer Dim y As Integer Dim r As Rectangle If Not parent Is Nothing Then r = parent.ClientRectangle x = r.Width - frm.Width + parent.Left y = r.Height - frm.Height + parent.Top Else r = Screen.PrimaryScreen.WorkingArea x = r.Width - frm.Width y = r.Height - frm.Height End If x = CInt(x / 2) y = CInt(y / 2) frm.StartPosition = FormStartPosition.Manual frm.Location = New Point(x,y) End Sub
如何定义,如何让这个子窗体正确放置在屏幕中间或其他形式?
代码是错的.此代码运行得足够晚也很重要,构造函数太早了.请务必从Load事件中调用它,此时表单已正确自动调整并根据用户的首选项进行调整,StartPosition属性不再重要.固定:
原文链接:https://www.f2er.com/vb/255963.htmlPublic Shared Sub CenterForm(ByVal frm As Form,Optional ByVal parent As Form = Nothing) '' Note: call this from frm's Load event! Dim r As Rectangle If parent IsNot Nothing Then r = parent.RectangleToScreen(parent.ClientRectangle) Else r = Screen.FromPoint(frm.Location).WorkingArea End If Dim x = r.Left + (r.Width - frm.Width) \ 2 Dim y = r.Top + (r.Height - frm.Height) \ 2 frm.Location = New Point(x,y) End Sub
顺便提一下,实际实现Load事件处理程序的极少数理由之一.