2013-04-02 72 views
0

我有一個MDI(父窗體)窗體和2個其他窗體。在form1上有一個按鈕,位置是(X:100,Y:200)。當用戶通過Form1單擊按鈕時,我需要打開另一個窗體「Form2」。 Form2的位置應該是按鈕的右側中間(發件人)。設置窗體位置與父窗體按鈕相關

我寫這篇文章的代碼

 
    Private Sub UpdateLocation(ByVal element As Control, ByVal frm As Form) 
     Dim p As New Point(element.Location) 
     p = element.PointToScreen(p) 
     p.X = p.X + element.Width + 10 
     p.Y = p.Y/2 

     Debug.Print(p.ToString) 
     frm.Location = p 
     frm.BringToFront() 
    End Sub 

,但並不如預期窗體2的位置。 在我呼籲按鈕的單擊事件上面的函數

 
    UpdateLocation(form1.button1, form2) 

任何幫助將是明顯的。 在此先感謝。上面的代碼的

輸出是:

Button1_Click

幾個測試後我意識到point.x(location.x)正在工作,但不是point.y(location.y)

You can download the piece of code from here。你可以用它來檢查實際的問題。 VS2010是必需的。

+0

張貼一些截圖將有助於解決您的問題。 –

+0

[Button1_Click] http://goo.gl/yfbLS [Button2_Click] http://goo.gl/27wUM [Button3_Click] http://goo.gl/yfbLS –

回答

0

我想你需要考慮的按鈕的高度和形式,如果你想在中間:

Dim p As Point = Me.MdiParent.PointToScreen(element.Location) 
p.X += element.Width + 10 
p.Y += (element.Height/2) - (frm.Height/2) 
+0

抱歉,您的建議無效。爲了快速檢查問題,您現在可以下載代碼。請檢查主要帖子。 –

+0

@KartikGoyal更新後。在你的情況下,使用'Me.MdiParent.PointToScreen()' – LarsTech

0

試試這個,

Private Sub UpdateLocation(ByVal element As Control, ByVal frm As Form) 

     Dim p As New Point(element.Location) 
     p = element.parent.PointToScreen(p) 
     p.X = p.X + element.Width + 10 
     p.Y = p.Y + (element.height/2) 

     Debug.Print(p.ToString) 
     frm.Location = p 
     frm.BringToFront() 

End Sub 
+0

這是我在上述2個建議的幫助下出現的。 (element.Location) p = element.Parent.PointToScreen(p) pX = pX + element.Width + 10 pY + =(element.Height/2) - (frm.Height/2)' 上面的代碼使用1個MDI,1個孩子和1個正常形式。 我會對其他案例進行更多測試,並在稍後發佈結果。 感謝LarsTech和Rajaprabhu Aravindasam,你的建議足夠好。 –

0

「解決」,只是爲了再確認

 
Private Sub UpdateLocation(ByVal element As Control, ByVal frm As Form) 
     If IsNothing(element) Then 
      Exit Sub 
     End If 
     Dim p As New Point(element.Location) 
     p = element.Parent.PointToScreen(p) 
     p.X = p.X + element.Width + 5 
     p.Y += (element.Height/2) - (frm.Height/2) 

     frm.Location = p 
     frm.BringToFront() 
End Sub 

這段代碼在我所有的情況下都能正常工作。