|
VBA中的文框控件是没有句柄的,因此用apiFocus获取到的其实是文本框父级对象(如窗体、Frame等有句柄的对象)的句柄,这样一来,日历窗体对齐的其实是窗体的左下角。
要对齐到文本框,可以用下面的代码(注意:没考虑多层嵌套的情况,例如:窗体->Frame->文本框):
- Option Explicit
- Public gtxtDateInput As MSForms.TextBox '接受输入日期的文本框
- Public sDate '选择的日期
- Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
- Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
- Private Declare Function ReleaseDC Lib "user32" (ByVal hwnd As Long, ByVal hDC As Long) As Long
- Private Declare Function GetSystemMetrics Lib "user32" (ByVal nIndex As Long) As Long
- Private Const SM_CYCAPTION = 4
- Private Const SM_CXDLGFRAME = 7
- Private Const SM_CXFRAME = 32
- Private Declare Function GetDeviceCaps Lib "gdi32" (ByVal hDC As Long, ByVal nIndex As Long) As Long
- Private Const LOGPIXELSX = 88 ' Logical pixels/inch in X
- '===============================================================================================
- '-函数名称: CalendarFor
- '-功能描述: 打开日历窗体,选择相应的日期并赋值给指定文本框
- '-输入参数: DateInputCtl 必需的,要赋值的日期文本框对象
- '-返回参数: 返回从日历窗口中选择的日期
- '-其它说明:
- '-使用注意: 此函数必须和日历窗体MyCalendar一起配合使用
- '-返回参数: 无
- '-使用示例: CalendarFor Me.txtTextBox
- '-相关调用:
- '-创建日期: 2017-5-18
- '===============================================================================================
- Public Function CalendarFor(DateInputCtl As MSForms.TextBox)
- Set gtxtDateInput = DateInputCtl
- Dim hDC As Long, res As Long, borderWidth As Long, captionHeight As Long
- Dim lStyle As Long
-
-
- '获取屏幕DPI(屏幕分辨率,即每英寸像素数)--因为windows API的长度单位是像素,而VBA的长度单位是磅(1磅=1/72英寸),所以需要先获取DPI以便单位转换
- hDC = GetDC(0)
- res = GetDeviceCaps(hDC, LOGPIXELSX)
- ReleaseDC 0, hDC
- '获取窗体边框宽度
- borderWidth = GetSystemMetrics(SM_CXFRAME)
-
- '获取窗体标题栏高度
- captionHeight = GetSystemMetrics(SM_CYCAPTION)
- With MyCalendar
- '让日历窗体的左边距等于窗口的左边距 + 文本控件的左边距
- .Left = DateInputCtl.Parent.Left + DateInputCtl.Left + borderWidth * 72 / res
-
- '让日历窗体的上边路等于窗口的上边距 + 文本控件的上边距 + 文本控件的高度
- '(注:在Aero主题下,可能窗体边框会宽出来一块,盖住文本框下方几个像素)
- .Top = DateInputCtl.Parent.Top + DateInputCtl.Top + DateInputCtl.Height + (borderWidth + captionHeight) * 72 / res
- .Show
- End With
- End Function
复制代码 |
评分
-
1
查看全部评分
-
|