VBA开发,用户交互实例一则

作者在 2010-04-23 14:45:27 发布以下内容
创建命令选项
'这段代码其主体框架是处理GetEntity(选择实体)方法执行时可能遇到的错误。因为GetEntity方法太容易出错了,用户示选择到实体会出错,按下Esc或Enter键也会出错

'首先声明一个常量和一个Windows API函数,用于判断用户上一次按下的是否是Esc键。
'
“Retry:”是一个行标签,使用Goto Retry语句可以让程序执行到这一步时无条件转到Retry后面的语句继续执行。

Private Const VK_ESCAPE = &H1B '代表ESC键
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer

'功能:判断用户是否按下某一个键
'
输入:代表键的常量(从API Viewer中获得)
'
调用:API函数GetAsyncKeyState
'
返回:如果用户按下了指定的键,返回Ture;否则返回Flase
'
示例:
'
if CheckKey(&H1B)=Ture then do sth
Private Function CheckKey(lngKey As Long) As Boolean
    If GetAsyncKeyState(lngKey) Then
        CheckKey = True
    Else
        CheckKey = False
    End If
End Function

'设计过程中的测试
'
在GetEntity方法的前面执行IntializeUserInput方法,并为第一个参数输入128,这样GetEntity方法允许用户输入任意的字符
'
如果执行GetEntity方法遇到错误,就判断是否是“用户输入的是关键字”错误,如果是就判断用户输入的关键字是否与选项“输入字符串(T)”一致
'
如果用户输入了T来响应该选项,就继续提示用户输入一个字符串,并使用MseBox函数显示字符串的内容。
'
相反,如果用户在执行GetEntity方法时直接选择了一个文字对象,那么就直接使用MsgBox函数显示文字对象的内容。
Public Sub GetEntityWithOption()
    Dim objSelect As AcadEntity
    Dim basePnt As Variant
    '选择对象并判断类型
    On Error Resume Next
    
Retry:
    '定义有效的关键字
    Dim keywordList As String
    keywordList = "T"
    
    '调用InitializeUserInput方法来设置关键字
    ThisDrawing.Utility.InitializeUserInput 128, keywordList
    
    '获得用户的输入
    ThisDrawing.Utility.GetEntity objSelect, basePnt, vbNewLine & "选择文字对象[输入字符串(T)]:"
    
    If Err Then
        If StrComp(Err.Description, "用户输入的是关键字", 1) = 0 Then
            Dim inputString As String
            Err.Clear
            inputString = ThisDrawing.Utility.GetInput
            
            If StrComp(inputString, "t", vbTextCompare) = 0 Then
                inputString = ThisDrawing.Utility.GetString(ture, vbNewLine & "输入字符串:")
                MsgBox "文字内容:" & inputString
                Exit Sub
            End If
        End If
    End If
        
   '处理按下Esc键的错误
   If objSelect Is Nothing Then
        If CheckKey(VK_ESCAPE) = True Then
            Exit Sub
        Else
            GoTo Retry
        End If
    End If
    
    '处理未选择到实体的错误
    If Err <> 0 Then
        Err.Clear
        GoTo Retry
    End If
    
    '执行你的操作
    If TypeOf objSelect Is AcadText Then
        Dim objtext As AcadText
        Set objtext = objSelect
        MsgBox "文字内容:" & objtext.textString
    Else
        ThisDrawing.Utility.Prompt vbNewLine & "需要选择文字对象..."
        GoTo Retry
    End If
    
End Sub
本例取自《AutoCAD VBA & VB.NET开发 基础与实例教程》一书。
CAD二次开发 | 阅读 3078 次
文章评论,共1条
源本英明C
2010-06-17 13:44
1
hehe
游客请输入验证码
浏览95103次
最新评论