VB 如何获得光标在文本框中的行号和列号

 我来答
天蝎魔君
2010-12-26 · TA获得超过292个赞
知道小有建树答主
回答量:415
采纳率:0%
帮助的人:303万
展开全部
从别处搜的,不知道对你有没有帮助
一个例子:一个textbox,两个label 代码如下:

Option Explicit
Private Const EM_GETSEL = &HB0
Private Const EM_LINEFROMCHAR = &HC9
Private Const EM_LINEINDEX = &HBB

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 Sub Form_Load()
Dim lineno As Long, colno As Long
Call getCaretPos(Text1.hwnd, lineno, colno)
Label1.Caption = lineno
Label2.Caption = colno
End Sub

Public Sub getCaretPos(ByVal texthwnd As Long, lineno As Long, colno As Long )
Dim i As Long, j As Long
Dim lparam As Long, wparam As Long
Dim k As Long
'向文本框传递EM_GETSEL消息以获取从起始位置到光标所在位置的字符数
i = SendMessage(texthwnd, EM_GETSEL, wparam, lparam)
j = i / 2 ^ 16
'向文本框传递EM_LINEFROMCHAR消息根据获得的字符数确定光标所在行数
lineno = SendMessage(texthwnd, EM_LINEFROMCHAR, j, 0)
lineno = lineno + 1
'向文本框传递EM_LINEINDEX消息以获取所在列数
k = SendMessage(texthwnd, EM_LINEINDEX, -1, 0)
colno = j - k + 1
End Sub

Private Sub Form_Resize()
Text1.Width = Me.ScaleWidth
End Sub

Private Sub Text1_KeyUp(KeyCode As Integer, Shift As Integer)
Dim lineno As Long, colno As Long
Call getCaretPos(Text1.hwnd, lineno, colno)
Label1.Caption = lineno
Label2.Caption = colno
End Sub

Private Sub Text1_MouseDown(Button As Integer, Shift As Integer, X As Single , Y As Single)
Dim lineno As Long, colno As Long
Call getCaretPos(Text1.hwnd, lineno, colno)
Label1.Caption = lineno
Label2.Caption = colno
End Sub
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式