다음을 통해 공유


문자 자동완성 예제

자동 완성 샘플은 인식 API(애플리케이션 프로그래밍 인터페이스)를 사용하여 일본어로 문자 자동 완성을 구현하는 방법을 보여 줍니다.

이 샘플에서는 다음 기능이 사용됩니다.

  • 잉크 수집기 사용
  • 인식기 컨텍스트 사용

잉크 수집기와 인식기 컨텍스트를 초기화하기

InkCollectorInkRecognizerContext 개체는 이벤트를 발생시킬 수 있는 클래스로 선언됩니다.

Dim WithEvents ic As InkCollector
Dim WithEvents rc As InkRecognizerContext

양식의 Load 이벤트 처리기는 잉크 수집기를 만들고 잉크 수집기를 그림 상자에 연결하며 잉크 컬렉션을 사용하도록 설정합니다. 그런 다음, 이벤트 처리기는 기본 일본어 인식기를 로드하고 인식기 컨텍스트 '의 Guide 및 Strokes 속성을 초기화합니다.

Private Sub Form_Load()
   ' Set the ink collector to work in the small frame window
    Set ic = New InkCollector    ic.hWnd = fraBox.hWnd    ic.Enabled = True
    
    ' Get the Japanese recognizer
    LoadRecognizer

    ' Initialize the recognizer context
    Dim Guide As New InkRecognizerGuide
    Dim FrameRectangle As New InkRectangle
    Dim Top As Long
    Dim Bottom As Long
    Dim Left As Long
    Dim Right As Long
    Top = 0
    Left = 0
    Bottom = fraBox.ScaleHeight
    Right = fraBox.ScaleWidth
    ic.Renderer.PixelToInkSpace Me.hdc, Top, Left
    ic.Renderer.PixelToInkSpace Me.hdc, Bottom, Right
    FrameRectangle.Bottom = Bottom
    FrameRectangle.Top = Top
    FrameRectangle.Left = Left
    FrameRectangle.Right = Right
    Guide.Columns = 1
    Guide.Rows = 1
    Guide.Midline = -1 ' Do not use midline
    Guide.DrawnBox = FrameRectangle
    Guide.WritingBox = FrameRectangle
    Set rc.Guide = Guide
    
    ' Set the strokes collection on the recognizer context
    Set ink = ic.ink    Set rc.Strokes = ic.ink.Strokes
End Sub

기본 일본어 인식기 로드

InkRecognizersGetDefaultRecognizer 메서드는 일본어용 기본 인식기를 검색하기 위해 호출됩니다. 다음으로 IInkRecognizer 개체의 Languages 속성을 확인하여 인식기가 일본어를 지원하는지 확인합니다. 이 경우 인식기 CreateRecognizerContext 메서드를 사용하여 폼에 대한 인식기 컨텍스트를 생성합니다.

Private Sub LoadRecognizer()
    On Error GoTo NoRecognizer
    ' Get a Japanese recognizer context
    Dim recos As New InkRecognizers
    Dim JapaneseReco As IInkRecognizer
    Set JapaneseReco = recos.GetDefaultRecognizer(&H411)
    If JapaneseReco Is Nothing Then
        MsgBox "Japanese Recognizers are not installed on this system. Exiting."
        End
    End If
    
    ' Check that this is indeed a Japanese recognizer
    Dim IsJapanese As Boolean
    Dim lan As Integer
    IsJapanese = False
    For lan = LBound(JapaneseReco.Languages) To UBound(JapaneseReco.Languages)
        If JapaneseReco.Languages(lan) = &H411 Then
            IsJapanese = True
        End If
    Next lan
    If Not IsJapanese Then
        MsgBox "Japanese Recognizers are not installed on this system. Exiting."
        End
    End If
    Set rc = JapaneseReco.CreateRecognizerContext
    Exit Sub
NoRecognizer:
    MsgBox "Japanese Recognizers are not installed on this system. Exiting."
    End
End Sub

Stroke 이벤트 처리

Stroke 이벤트 처리기는 먼저 인식기 컨텍스트에서 백그라운드 인식을 중지합니다. 그런 다음 인식기 컨텍스트의 Strokes 속성에 새 스트로크를 추가합니다. 마지막으로, 인식기 컨텍스트의 InkRecognizerCharacterAutoCompletionMode 속성을 설정하고 세 문자 자동 완성 모드 각각에 대해 인식기 컨텍스트의 BackgroundRecognizeWithAlternates 메서드를 호출합니다. BackgroundRecognizeWithAlternates 메서드 호출의 CustomData 매개 변수는 RecognitionWithAlternates 이벤트에서 반환되는 인식 결과를 식별하는 데 사용됩니다.

Private Sub ic_Stroke(ByVal Cursor As MSINKAUTLib.IInkCursor, ByVal Stroke As MSINKAUTLib.IInkStrokeDisp, Cancel As Boolean)

    ' Stop the unfinished recognition processes
    rc.StopBackgroundRecognition

    ' Add the new stroke
    rc.Strokes.Add Stroke

    ' Get a result for all three CAC modes
    rc.CharacterAutoCompletionMode = IRCACM_Full rc.BackgroundRecognizeWithAlternates 0 rc.CharacterAutoCompletionMode = IRCACM_Prefix rc.BackgroundRecognizeWithAlternates 1 rc.CharacterAutoCompletionMode = IRCACM_Random rc.BackgroundRecognizeWithAlternates 2
End Sub

대체 이벤트를 사용하여 인식 처리

RecognitionWithAlternates 이벤트에 대한 처리기는 먼저 RecognitionStatus 매개 변수를 확인합니다. 인식에 오류가 있는 경우 이벤트 처리기는 인식 결과를 무시합니다. 그렇지 않으면 이벤트 처리기가 적절한 그림 상자에 RecognitionResult 매개 변수를 추가하고 결과 문자열을 저장합니다. CustomData 매개 변수는 BackgroundRecognizeWithAlternates 메서드에 대한 호출에서 설정되며 인식기 컨텍스트에서 사용된 문자 자동 완성 모드를 식별합니다.

Private Sub rc_RecognitionWithAlternates(ByVal RecognitionResult As MSINKAUTLib.IInkRecognitionResult, ByVal vCustomParam As Variant, ByVal RecognitionStatus As MSINKAUTLib.InkRecognitionStatus)
    ' Get the alternates from the recognition result
    ' and display them in the right place
    Dim ResultString As String
    Dim alts As IInkRecognitionAlternates
    Dim alt As IInkRecognitionAlternate
        
    On Error GoTo EndFunc

    If RecognitionStatus = IRS_NoError Then
        ' Fill a string with all the characters for this CAC mode
        Set alts = RecognitionResult.AlternatesFromSelection
        For Each alt In alts
            ResultString = ResultString + alt.String
        Next alt
        ' Display the string
        Dim r As RECT
        r.Left = 0
        r.Top = 0
        r.Right = 1000
        r.Bottom = 1000
        PctResult(vCustomParam).Cls
        DrawText PctResult(vCustomParam).hdc, StrPtr(ResultString), Len(ResultString), r, 0
        If vCustomParam = 0 Then
            FullCACText = ResultString
        Else
            If vCustomParam = 1 Then
                PrefixCACText = ResultString
            Else
                If vCustomParam = 2 Then
                    RandomCACText = ResultString
                End If
            End If
        End If
    End If
    Exit Sub
EndFunc:
    MsgBox Err.Description
End Sub

형태 그리기

Paint 이벤트 처리기는 결과 그림 상자를 지우고 저장된 인식 결과를 추가합니다.

스트로크 삭제

양식의 CmdClear_Click 메서드는 Clear 명령을 처리합니다. InkCollector 현재 잉크를 수집하는 경우 메시지 상자가 표시되고 명령이 무시됩니다. 그렇지 않으면 이벤트 처리기는 백그라운드 인식을 중지하고 인식기 컨텍스트의 Strokes 속성을 지우고 폼의 InkDisp 개체에서 스트로크를 삭제합니다. 그런 다음, 이벤트 처리기는 잉크 수집기가 연결된 그림 상자를 다시 그리고 인식 문자열 및 그림 상자를 지웁니다.

If Not (ic.CollectingInk) Then

    ' Stop the unfinished recognition processes
    rc.StopBackgroundRecognition

    ' ...
    Set rc.Strokes = Nothing

    ' Delete all the strokes from the ink object
    ic.Ink.DeleteStrokes strokesToDelete

    ' Refresh the window
    fraBox.Refresh

    ' refresh the recognizer context
    Set rc.Strokes = ic.Ink.Strokes

    ' Clear the result strings
    FullCACText = ""
    PrefixCACText = ""
    RandomCACText = ""

    ' Clear the result windows
    PctResult(0).Cls
    PctResult(1).Cls
    PctResult(2).Cls

Else
    MsgBox "Cannot clear ink while the ink collector is busy."
End If