rainstormmaster的blog
rainstormmaster的blog

通常我们要获得EDIT编辑框的某一行的文本,只要用sendmessage发送EM_GETLINE消息就可以了,然而当我们试图发送EM_GETLINE消息给Richtextbox控件时,却得不到正确的数据,这在Richtextbox控件同时包含中文和英文时表现的很明显,而如果Richtextbox控件的内容只有英文时,发送EM_GETLINE消息则可以得到正确的数据(写到这里,不由得开始羡慕米国人不需要同unicode打交道)。

我的做法是发送EM_GETTEXTRANGE消息给Richtextbox控件,代码如下:

Option Explicit

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
 
Private Const GTL_NUMBYTES = 16&
Private Const EM_LINEINDEX = &HBB
Private Const EM_GETLINECOUNT = &HBA
Private Const EM_LINELENGTH = &HC1
Const WM_USER = &H400
Const EM_GETTEXTRANGE = (WM_USER + 75)
Private Type CHARRANGE   'cr
    cpMin As Long
    cpMax As Long
End Type
Private Type TEXTRANGE
  chrg As CHARRANGE
  lpstrText As String ' allocated by caller, zero terminated by RichEdit
End Type

Private Function mGetRTLine(RT As RichTextBox, ByVal LineNum As Long, getRTLine As String) As Boolean
    Dim LineCount As Long
    Dim lc As Long, j As Long
    Dim charFrom As Long
    Dim charEnd As Long
    Dim CR As CHARRANGE
    Dim TR As TEXTRANGE
    If LineNum < 1 Then
        getRTLine = vbNullString
        mGetRTLine = False
        Exit Function
    End If
    LineCount = SendMessage(RT.hWnd, EM_GETLINECOUNT, ByVal 0&, ByVal 0&)
    If LineNum > LineCount Then
        getRTLine = vbNullString
        mGetRTLine = False
        Exit Function
    End If
    charFrom = SendMessage(RT.hWnd, EM_LINEINDEX, LineNum - 1, ByVal 0&)
    lc = SendMessage(RT.hWnd, EM_LINELENGTH, ByVal charFrom, ByVal 0&)
    If lc = 0 Then
        getRTLine = vbNullString
        mGetRTLine = True
        Exit Function
    End If
    charEnd = charFrom + lc
    CR.cpMin = charFrom
    CR.cpMax = charEnd
    TR.chrg = CR
    TR.lpstrText = Space(lc)
    j = SendMessage(RT.hWnd, EM_GETTEXTRANGE, ByVal 0&, TR)
    If j = 0 Then
        getRTLine = vbNullString
        mGetRTLine = False
        Exit Function
    Else
        getRTLine = TR.lpstrText
        mGetRTLine = True
    End If
End Function

调用方法为:

Dim S As String, FLAG As Boolean
FLAG = mGetRTLine(Me.RichTextBox1, 1, S)

其中s装载的就是RichTextBox控件中第1行的文本

posted on 2005-11-20 09:23  学剑学诗两不成  阅读(2203)  评论(0)    收藏  举报