屏幕或父母的中心表格

时间:2013-10-15 22:18:36

标签: vb.net

由于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

如果定义了如何使此子表格正确放置在屏幕中间或其他表格中?

5 个答案:

答案 0 :(得分:27)

我知道这是一个老帖子,这并没有直接回答这个问题,但是对于偶然发现这个问题的其他人来说,只需要完成一个表格就可以完成而无需你自己编写程序。

"range_end" def syn(event=None): textPad.mark_set("range_start", "1.0") data = textPad.get("1.0", "end-1c") for token, content in lex(data, PythonLexer()): textPad.mark_set("range_end", "range_start + %dc" % len(content)) textPad.tag_add(str(token), "range_start", "range_end") textPad.mark_set("range_start", "range_end") 允许您将表单置于参考屏幕或引用父表单的中心,具体取决于你需要哪一个。

需要注意的一点是,在加载表单之前,必须调用这些过程必须。最好在form_load事件处理程序中调用它们。

示例代码:

System.Windows.Forms.Form.CenterToScreen()

答案 1 :(得分:20)

代码是错的。此代码运行得足够晚也很重要,构造函数太早了。请务必从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事件处理程序的极少数理由之一。

答案 2 :(得分:6)

这也可能有用:

    myForm.StartPosition = FormStartPosition.CenterParent
    myForm.ShowDialog()

您也可以使用FormStartPosition.CenterScreen

答案 3 :(得分:0)

我遇到StartPosition = CenterParent无效的问题。我解决了它使用.ShowDialog()而不是.Show()调用表单:

' first you should set your form's Start Position as Center Parent
Private Sub button_Click(sender As Object, e As EventArgs) Handles button.Click
    MyForm.ShowDialog()
End Sub

答案 4 :(得分:0)

我今天为此苦苦挣扎。阅读文档后,我了解到 1. that you cannot call the CenterToParent method, 2. that you need to set the .StartingPosition Property of the form 和 3. “这个属性应该在表单显示之前设置,你可以在调用 Show 之前设置这个属性或者ShowDialog 方法”。 那么我是如何修复它的。是通过将代码放入实例化子窗体的子程序中,在父窗体上,如下所示。

Private Sub btnItemCategories_Click(sender As Object, e As EventArgs) Handles btnItemCategories.Click
    Dim objItemCategories As New frmItemCategories
    objItemCategories.StartPosition = FormStartPosition.CenterParent
    objItemCategories.ShowDialog(Me)
End Sub
相关问题