Visual Basic Codes
ActiveX
Miscellaneous
Applications
Code Snippets
Common Dialogs
Special Effects
Database Stuff
Date Time
Files Drives
Forms
Graphics Games
Internet Stuff
Multimedia
Other
Strings
Windows
Visual Basic > Forms sample source codes
How to center a form on a parent window.
How to center a form on a parent window. 'Note: This has only been tested with VB 3 and VB 4-16, if you convert ' This procedure centers a Form over a Parent window. ' This dialog-centering algorithm works well when you're ' not sure of the resolution of the target computer. ' Declare this Type in a .Bas module: Type RECT Left As Integer Top As Integer Right As Integer Bottom As Integer End Type ' Declare this API Declare Sub GetWindowRect Lib "User" (ByVal hWnd%, lpRect As RECT) ' Add the DialogCenterParent rountine: Sub DialogCenterParent (ByVal hWndParent As Integer, frmDialog As Form) Dim iLeft As Integer Dim iTop As Integer Dim iMidX As Integer Dim iMidY As Integer Dim rcParent As RECT ' Find the ideal center point. If hWndParent = 0 Then 'No parent, so center over the enter screen iMidX = Screen.Width / 2 iMidY = Screen.Height / 2 Else 'Center over the form's parent. Call GetWindowRect(hWndParent, rcParent) ' Next 2 lines as one single line. iMidX = ((rcParent.Left * Screen.TwipsPerPixelX) + (rcParent.Right * Screen.TwipsPerPixelY)) / 2 ' Next 2 lines as one single line. iMidY = ((rcParent.Top * Screen.TwipsPerPixelY) + (rcParent.Bottom * Screen.TwipsPerPixelY)) / 2 End If ' Find the form's upper left based on that iLeft = iMidX - (frmDialog.Width / 2) iTop = iMidY - (frmDialog.Height / 2) ' If the form is outside the screen, move it inside If iLeft < 0 Then iLeft = 0 ElseIf (iLeft + frmDialog.Width) > Screen.Width Then iLeft = Screen.Width - frmDialog.Width End If If iTop < 0 Then iTop = 0 ElseIf (iTop + frmDialog.Height) > Screen.Height Then iTop = Screen.Height - frmDialog.Height End If ' Move the form to it's new position frmDialog.Move iLeft, iTop End Sub ' Call the routine in the Form_Load event of the form to center: ' Substitute your Parent for Form1 Call DialogCenterParent(Form1.hWnd, Me)
Privacy Policy
|
Link to Us
|
Links