VB6 中的 Ctrl+退格键?

Ctrl+Backspace in VB6?

我使用以下 VB6 代码来 Ctrl+Backspace 单词,但它只在单词用空格分隔时有效。如果单词由任何特殊字符分隔,我需要它才能工作:。 -#等

Public Sub DelLastWord(tb As TextBox)
    Dim WordStart As String
    Dim Trimmed As String
    Dim curpos As Long

    curpos = tb.SelStart
    Trimmed = Trim$(Left$(tb.Text, curpos))
    If LenB(Trimmed) Then
        WordStart = InStrRev(Trimmed, Space$(1), Len(Trimmed))
        tb.SelStart = WordStart
        tb.SelLength = curpos - WordStart
        tb.SelText = vbNullString
    End If
End Sub

有人可以给我任何建议或代码来处理特殊字符吗?

只需将您的 InStrRev 调用替换为能够找到您想要的内容即可。转到字符串的末尾,向后循环,并在第一个“特殊”字符处停止。

像这样的东西是基本的,但它可以完成工作。我确信有可用的优化,比如不使用 NonSpecial 字符串,而是用数学检查 ASCII 代码,但你明白了。这种方式的好处是易于阅读and/or更改哪些字符是特殊字符。

Public Function FindLastSpecialChar(ByVal Str As String) As Long
  Const NonSpecial As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  Dim I As Long
  
  For I = Len(Str) To 1 Step -1
    If InStr(NonSpecial, Mid(Str, I, 1)) = 0 Then
      FindLastSpecialChar = I
      Exit Function
    End If
  Next
End Function

上面的returns 4下面每一个window:

  • ?findlastspecialchar("abc john")
  • ?findlastspecialchar("abc;john")
  • ?findlastspecialchar("abc.john")
  • ?findlastspecialchar("abc+john")

我会从插入点向后循环,直到找到分隔符。像这样:

Public Sub DelLastWord(tb As TextBox)
   Dim i As Long
   Dim curpos As Long

   curpos = tb.SelStart

   For i = curpos To 1 Step -1
      If isSeparator(Mid(tb.Text, i, 1)) Or i = 1 Then
         tb.SelStart = i - 1
         tb.SelLength = curpos - i + 1
         tb.SelText = vbNullString
         Exit Sub
      End If
   Next
End Sub

Private Function isSeparator(char As String) As Boolean
   'if the character is not a letter or number
   'then it is a separator

   If Asc(char) >= 48 And Asc(char) <= 57 Then Exit Function
   If Asc(char) >= 65 And Asc(char) <= 90 Then Exit Function
   If Asc(char) >= 97 And Asc(char) <= 122 Then Exit Function
   
   isSeparator = True
End Function