Tuesday, September 23, 2008

How to Capitalized the first character of the text in Visual Basic 6

Sub Text1_KeyPress(KeyAscii As Integer)        If Text1.SelStart = 0 Then           ' This is the first character, so change to uppercase.           KeyAscii = Asc(UCase$(Chr$(KeyAscii)))       Else           ' If the previous character is a space, capitalize           ' the current character.           If Mid$(Text1, Text1.SelStart, 1) = Space$(1) Then               KeyAscii = Asc(UCase$(Chr$(KeyAscii)))           End If       End If   End Sub  

The functionality in the KeyPress event is tied explicitly to Text1. To reuse this code, you would have to cut and paste it and then change every reference made to Text1 to the new control. The code would be truly reusable if written like this:

Sub Text1_KeyPress(KeyAscii As Integer)       KeyAscii = nConvertToCaps(Text1, KeyAscii)   End Sub    Function nConvertToCaps(ByVal ctl As Control, _       ByRef nChar As Integer) As Integer        If ctl.SelStart = 0 Then           ' This is the first character, so change to uppercase.           nChar = Asc(UCase$(Chr$(nChar)))       Else           ' If the previous character is a space, capitalize           ' the current character.           If Mid$(ctl, ctl.SelStart, 1) = Space$(1) Then               nChar = Asc(UCase$(Chr$(nChar)))           End If       End If        nConvertToCaps = nChar   End Function

No comments: