一个名为txtEdit的富文本框。
Private Function strLeft(str As String, nLen As Long) As String
    If nLen <= 0 Then
        strLeft = ""
    Else
        strLeft = Left(str, nLen)
    End If
End Function
Private Sub txtEdit_KeyPress(KeyAscii As Integer)
    If KeyAscii = 13 Then
        txtEdit.Text = strLeft(txtEdit.Text, txtEdit.SelStart) & vbCrLf & "    " & LTrim(Mid(txtEdit.Text, txtEdit.SelStart + 1))
        txtEdit.SetFocus
        txtEdit.SelStart = Len(txtEdit.Text)
    End 但是这段代码的光标和键盘操作不同步,我需要它完全像word里一样,光标总是在即时编辑位置闪烁。

解决方案 »

  1.   

    Private Function strLeft(str As String, nLen As Long) As String
        If nLen <= 0 Then
            strLeft = ""
        Else
            strLeft = Left(str, nLen)
        End If
    End Function
    Private Sub txtEdit1_KeyPress(KeyAscii As Integer)
        If KeyAscii = 13 Then
            Dim lSelPos As Long
            lSelPos = txtEdit.SelStart
            txtEdit.Text = strLeft(txtEdit.Text, txtEdit.SelStart) & vbCrLf & "    " & LTrim(Mid(txtEdit.Text, txtEdit.SelStart + 1))
            txtEdit.SetFocus
            txtEdit.SelStart = lSelPos
            KeyAscii = 0
        End If
    End Sub
      

  2.   

    我的意思是,比如一按按钮cmd1,就在光标处插入“cmd1”字符串。
      

  3.   

    还有,在句中用回车键时照Private Function strLeft(str As String, nLen As Long) As String
        If nLen <= 0 Then
            strLeft = ""
        Else
            strLeft = Left(str, nLen)
        End If
    End Function
    Private Sub txtEdit1_KeyPress(KeyAscii As Integer)
        If KeyAscii = 13 Then
            Dim lSelPos As Long
            lSelPos = txtEdit.SelStart
            txtEdit.Text = strLeft(txtEdit.Text, txtEdit.SelStart) & vbCrLf & "    " & LTrim(Mid(txtEdit.Text, txtEdit.SelStart + 1))
            txtEdit.SetFocus
            txtEdit.SelStart = lSelPos
            KeyAscii = 0
        End If
    End Sub在句末按回车键时则跳到下一行,并在开头空两格,像这样的效果:
    Private Sub txtEdit_KeyPress(KeyAscii As Integer)
       If KeyAscii = vbKeyReturn Then
          KeyAscii = 0
          txtEdit.Text = txtEdit.Text & vbCrLf & "    "
          txtEdit.SelStart = Len(txtEdit.Text)
       End If
    End Sub现在如何把上述两个条件整合起来,我发现这两段程序不能并存。
      

  4.   

    Private Sub txtEdit_KeyPress(KeyAscii As Integer)
        txtEdit.SelText = chr(KeyAscii)
    End Sub