テキストボックスの現在選択されている範囲を取得するには

テキストボックスの現在選択されている範囲を取得してみます。
キーワードは「EM_GETSEL」メッセージです。
EM_GETSELメッセージはテキストボックスで現在選択されている開始文字位置と終了文字位置を返します
0を与えると、現在のテキストカーソル(キャレット)のある位置を返します。

実行時の様子

'指定のウィンドウにメッセージを送る
Private Declare Function SendMessageRef Lib "user32.dll" Alias "SendMessageA" _
    (ByVal hWnd As Long, ByVal MSG As Long, wParam As Long, lParam As Long) As Long
'テキストボックスのメッセージ
Private Const EM_GETSEL = &HB0                          '選択されたテキストの最初と最後の

'文字インデックスを取得する Private Function LWORD(ByVal LongValue As Long) As Integer '長整数値から下位ワードを取得する If (LongValue And &HFFFF&) > &H7FFF Then LWORD = (LongValue And &HFFFF&) - &H10000 Else LWORD = LongValue And &HFFFF& End If End Function
Private Function HWORD(ByVal LongValue As Long) As Integer '長整数値から上位ワードを取得する HWORD = (LongValue And &HFFFF0000) \ &H10000 End Function
Private Sub Text1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) Dim strIndex As Long, endIndex As Long, rc As Long, txt As String If Me.Text1.SelLength > 0 Then '選択されている文字列がある場合 rc = SendMessageRef(Me.Text1.hWnd, EM_GETSEL, strIndex, endIndex) txt = Me.Text1.Text strIndex = strIndex + 1 endIndex = endIndex + 1 'Me.Label1.Caption = Mid(txt, strIndex, endIndex - strIndex + 1) Me.Label1.Caption = Mid(txt, Me.Text1.SelStart + 1, Me.Text1.SelLength + 1) Else Me.Label1.Caption = "" End If End Sub
ダウンロード