在Vb中如text和label控件是没有垂直居中功能的,但是可以变通就是给文字加空行。
'加一个 Text1 一个 Command1 :
Dim aa As String, i As Integer, jj As Integer, maxline As Integer, LineCnt As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Const EM_GETLINECOUNT = &HBA
Private Sub Form_Load()
'窗体与Command1居中
Me.Move (Screen.Width - Me.Width) \ 2, (Screen.Height - Me.Height) \ 2
Command1.Move (Me.Width - Command1.Width) \ 2, Text1.Height + Text1.Top + 200
Command1.Caption = "居中显示"
Text1.Alignment = 2 'TextBox 水平居中显示
aa = "Attn:楼主"
aa = aa & Chr(13) & Chr(10)
aa = aa & "呵呵你的问题都好奇怪,但也让我学了不少!"
aa = aa & Chr(13) & Chr(10)
aa = aa & "我也想不出其它的好方法"
aa = aa & Chr(13) & Chr(10)
aa = aa & "你认为这样行吗?"
Text1.Text = aa
End Sub
Private Sub Command1_Click()
LineCnt = TextBoxLineCnt(Text1)
'每增加一行加上180,当然是以默认的字体大小而言
maxline = Text1.Height \ 180 '计算textbox能装下几行
jj = (maxline - LineCnt) \ 2 '垂直居中,(textbox总行数-Text1的总行数)整除2
For i = 1 To jj '装上几行空白
Text1.Text = Chr(13) & Chr(10) & Text1.Text
Next i
MsgBox "总共有" & CStr(LineCnt) & "行文字,看看垂直居中了吗?"
End Sub
Public Function TextBoxLineCnt(ctl As TextBox) As Long '计算总行数的函数
TextBoxLineCnt = SendMessage(ctl.hwnd, EM_GETLINECOUNT, 0, 0)
End Function
除了水平具有居中功能外并不具备垂直居中功能。
不过要实现垂直居中功能只能同时调整label的控件大小和字体大小了:
Label1.Width
Label1.Height
Label1.FontSize
Label空件的Alignment属性选择2-Center
抱歉没看清是垂直
Label空件不能直接设置垂直居中,只能调节字号或调节高度
如果是为了界面美观,需要背景(颜色)可以用Shape控件与文本框组合起来实现