在屏幕或父级上居中表单 [英] Center form on screen or on parent

查看:31
本文介绍了在屏幕或父级上居中表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Since built in functionality for positioning forms in VB.NET are not always suitable to use I try to make my sub to do that.

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

But I missed something...

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

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

How to get this sub to place form correctly in the middle of the screen or other form if is defined?

推荐答案

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

The code is just wrong. It is also essential that this code runs late enough, the constructor is too early. Be sure to call it from the Load event, at that time the form is properly auto-scaled and adjusted for the user's preferences, the StartPosition property no longer matters then. Fix:

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

Incidentally, one of the very few reasons to actually implement the Load event handler.

这篇关于在屏幕或父级上居中表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆