【转】VB 技巧一

改变 ListIndex而不发生 Click 事件

在修改 Combo 或 Listview 的ListIndex 时, 会发生 Click 事件, 下面的函数可以阻止该事件。

声明:

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 CB_GETCURSEL = &H147

Const CB_SETCURSEL = &H14E

Const LB_SETCURSEL = &H186

Const LB_GETCURSEL = &H188

函数:

Public Function SetListIndex(lst As Control, _

ByVal NewIndex As Long) As Long

 

If TypeOf lst Is ListBox Then

Call SendMessage(lst.hWnd, _

LB_SETCURSEL, NewIndex, 0&)

SetListIndex = SendMessage(lst.hWnd, _

LB_GETCURSEL, NewIndex, 0&)

ElseIf TypeOf lst Is ComboBox Then

Call SendMessage(lst.hWnd, _

CB_SETCURSEL, NewIndex, 0&)

SetListIndex = SendMessage(lst.hWnd, _

CB_GETCURSEL, NewIndex, 0&)

End If

End Function

调整 Combo 下拉部分的宽度
声明:

Private Declare Function SendMessage Lib _

"USER32" Alias "SendMessageA" _

(ByVal hwnd As Long, ByVal Msg As Long, _

ByVal wParam As Long, ByVal lParam As Long) As Long

Private Const CB_GETDROPPEDWIDTH = &H15F

Private Const CB_SETDROPPEDWIDTH = &H160

Private Const CB_ERR = -1

函数:

' 取得 Combo 下拉的宽度

' 可以利用该函数比例放大或缩小宽度

Public Function GetDropdownWidth(cboHwnd As Long) As Long

Dim lRetVal As Long

lRetVal = SendMessage(cboHwnd, CB_GETDROPPEDWIDTH, 0, 0)

If lRetVal <> CB_ERR Then

GetDropdownWidth = lRetVal

'单位为 pixels

Else

GetDropdownWidth = 0

End If

End Function

'设置 Combo 下拉的宽度

'单位为 pixels

Public Function SetDropdownWidth(cboHwnd As _

Long, NewWidthPixel As Long) As Boolean

Dim lRetVal As Long

lRetVal = SendMessage(cboHwnd, _

CB_SETDROPPEDWIDTH, NewWidthPixel, 0)

If lRetVal <> CB_ERR Then

SetDropdownWidth = True

Else

SetDropdownWidth = False

End If

End Function

Combo的自动查询技术
Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long

Public Const CB_FINDSTRING = &H14C

Private Sub Combo1_Change()

Dim iStart As Integer

Dim sString As String

Static iLeftOff As Integer

iStart = 1

iStart = Combo1.SelStart

If iLeftOff <> 0 Then

Combo1.SelStart = iLeftOff

iStart = iLeftOff

End If

sString = CStr(Left(Combo1.Text, iStart))

Combo1.ListIndex = SendMessage(Combo1.hwnd, _

B_FINDSTRING, -1, ByVal CStr(Left( _

ombo1.Text, iStart)))

 

If Combo1.ListIndex = -1 Then

iLeftOff = Len(sString)

combo1.Text = sString

End If

Combo1.SelStart = iStart

iLeftOff = 0

End Sub

静态变量 iLeftOff 指定了字符长度。

自动选择 Text 的内容
在使用 VFP 的应用进行录入时,每进入一个录入框,就自动选择该框中的所有内容。利用以下的代码,也可实现类似的功能。

Private Sub MyTextBox_GotFocus()

AutoSelect MyTextBox

End Sub

 

Sub AutoSelect(SelObject As Control)

SelObject.SelStart = 0

If TypeOf SelObject Is MaskEdBox Then

SelObject.SelLength = Len(SelObject.FormattedText)

Else

If TypeOf SelObject Is TextBox Then

SelObject.SelLength = Len(SelObject.Text)

End If

End If

End Sub