VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > vb >
  • vb教程之用VB6分离出文本框的单词

编程爱好者一定使用过金山词霸的即指即译功能,它实际上是首先从文本中分离出鼠标所在位置的单词,然后对照英汉信息数据库的相关信息进行翻译。下面的代码演示了如何从一个RECHTEXT文本框中分离出单词,并且将它显示在一个标签控件中。 

  启动vb6,建立一个标准exe工程,单击“工程”――“部件”,选中Microsoft rich text control6.0,单击“确定”按钮,然后在窗体中添加该控件,命名为rchMainText,在窗体底部添加一个标签控件命名为label1,双击窗体,写入以下代码: 

  Option Explicit 

  Private Const EM_CHARFROMPOS& = &HD7‘返回鼠标所在位置的字符指针 

  Private Type POINTAPI 

   X As Long 

   Y As Long 

  End Type‘鼠标位置坐标 

  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 

  Public Function RichWordOver(rch As RichTextBox, X As Single, Y As Single) As String 

   '当鼠标移动到richtext控件时,分离出当前的单词 

  Dim pt As POINTAPI ‘鼠标指针坐标 

  Dim pos As Integer 

  Dim start_pos As Integer 

  Dim end_pos As Integer 

  Dim ch As String 

  Dim txt As String 

  Dim txtlen As Integer 

  pt.X = X \ Screen.TwipsPerPixelX 

  pt.Y = Y \ Screen.TwipsPerPixelY 

  ‘获得鼠标所在位置 

  pos = SendMessage(rch.hWnd, EM_CHARFROMPOS, 0&, pt) 

  If pos <= 0 Then Exit Function 

   txt = rch.Text 

   For start_pos = pos To 1 Step -1 

    ch = Mid$(rch.Text, start_pos, 1) 

    '从当前字符开始查找0-9、a-z、A-Z和“-”以外的字符,因为它们不‘可能是单词的组成,据此可以判断出本单词第一个字母的位置 

    If Not ( _(ch >= "0" And ch <= "9") Or _(ch >= "a" And ch <= "z") Or _ 
(ch >= "A" And ch <= "Z") Or _ch = "_") Then Exit For 

   Next start_pos ‘找到后退出循环 

   start_pos = start_pos + 1‘纪录本单词开始位置 

   '从鼠标当前位置查找本单词的最后一个字母位置,判断原理同上 

   txtlen = Len(txt) 

   For end_pos = pos To txtlen 

    ch = Mid$(txt, end_pos, 1) 

    ' Allow digits, letters, and underscores. 

    If Not ( (ch >= "0" And ch <= "9") Or (ch >= "a" And ch <= "z") Or _ 
(ch >= "A" And ch <= "Z") Or _ 
ch = "_" _ 
) Then Exit For ‘找到后退出循环 

   Next end_pos 

   end_pos = end_pos - 1‘纪录最后一个单词位置 

   If start_pos <= end_pos Then 
    
    RichWordOver = Mid$(txt, start_pos, end_pos - start_pos + 1) 

    '利用MID函数取出该单词 

   End Function 

  Private Sub Form_Load() ‘程序运行时初始化RICHTEXT 

   On Error Resume Next 

   Me.Caption = App.Title '添加应用程序标题 

   Me.Left = (Screen.Width - Me.Width) / 2 

   Me.Top = (Screen.Height - Me.Height) / 2 '窗体具中 

   rchMainText.Text = "Button As Integer, Shift As Integer, X As Single, Y As Single" 

  End Sub 

  Private Sub rchMainText_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) 

   '当鼠标移动到RICHTEXT时,开始激活单词分离过程 

   Dim txt As String‘分离出的单词 

   txt = RichWordOver(rchMainText, X, Y)‘单词判断 

   If label1.Caption <> txt Then 

     label1.Caption = txt 

     ‘将返回的单词传递给LABEL1标签 

   End Sub 

  Private Sub Form_Unload(Cancel As Integer) 

    End 

  End Sub‘程序结束

相关教程