VB6 Tip: Changing text alignment for forms and picture boxes
Takeaway: Change the displayed alignment of text on a form or picture box in Visual Basic 6 with a Windows API call.
A Visual Basic 6 program can display text on a form or a picture box using the Print method. The text's location is determined by the destination object's CurrentX and CurrentY properties. The text is always left-aligned at this position, starting at the location (CurrentX, CurrentY) and extending to the right. VB doesn't have a provision for changing this alignment setting, but you can do it with a Windows API call.
You'll use theSetTextAlign API function, whose declaration is:
Declare Sub SetTextAlign Lib "gdi32" (ByValhDC As Long, ByValwFlags As Long)hDC is the destination object's device context, which you obtain from its hDC property. wFlags is a value that specifies the desired alignment.
You specify the horizontal alignment using one of the following constants (which you must define in your program):
- TA_LEFT (value = 0),
- TA_RIGHT (value = 2), or
- TA_CENTER (value = 6)
You can also specify the vertical alignment with these constants:
- TA_TOP (value = 0),
- TA_BOTTOM (value = 8), or
- TA_BASELINE (value = 24)
Top alignment is the default; in other words, the top of the text is aligned with the CurrentY position. The other two options are:
- Bottom: The lowest any character descends, such as the descender on a "y" or "g."
- Baseline: The bottom of characters that don't have descenders, such as "a" and "w."
To apply both a horizontal and a vertical alignment, simply use the Or operator to combine the two flags. This code sets the alignment for Form1 to center, baseline:
Call SetTextAlign(Form1.hDC, TA_CENTER Or TA_BASELINENote that changing alignment doesn't affect text that is already on the form or picture box.
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!
SponsoredWhite Papers, Webcasts, and Downloads
- The Case for Virtual Local Area Networks (VLANs) Global Knowledge
- Ten Ways Hackers Breach Security Global Knowledge
- Effectively Managing Team Conflict Global Knowledge
- Top 10 Reasons Why TCP Is Reliable Global Knowledge
- Eleven Myths about 802.11 Wi-Fi Networks Global Knowledge
Article Categories
- Security
- Security Solutions, IT Locksmith
- Networking and Communications
- E-mail Administration NetNote, Cisco Routers and Switches
- CIO and IT Management
- Project Management, CIO Issues, Strategies that Scale
- Desktops, Laptops & OS
- Windows 2000 Professional, Microsoft Word, Microsoft Excel, Microsoft Access, Windows XP,
- Data Management
- Oracle, SQL Server
- Servers
- Windows NT, Linux NetNote, Windows Server 2003
- Career Development
- Geek Trivia
- Software/Web Development
- Web Development Zone, Visual Basic, .NET

