gpt4 book ai didi

vb.net - 在屏幕或父级上居中表单

转载 作者:行者123 更新时间:2023-12-04 04:43:03 25 4
gpt4 key购买 nike

由于 VB.NET 中用于定位表单的内置功能并不总是适合使用,因此我尝试让我的子程序做到这一点。

但我错过了一些东西......

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

如果已定义,如何让这个 sub 将表单正确地放置在屏幕或其他表单的中间?

最佳答案

只是代码错了。这段代码运行得足够晚也很重要,构造函数太早了。一定要从 Load 事件中调用它,那时表单会根据用户的偏好正确自动缩放和调整,然后 StartPosition 属性不再重要。使固定:

Public 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 事件处理程序的极少数原因之一。

关于vb.net - 在屏幕或父级上居中表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19392083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com