基本识别示例

此应用程序演示如何生成简单的 手写 识别应用程序。

此程序创建一个 InkCollector 对象来启用窗口 墨迹,以及一个默认 识别器上下文 对象。 收到从应用程序菜单触发的“Recognize!”命令后,收集的墨迹笔划将传递到识别器上下文。 最佳结果字符串显示在消息框中。

创建 RecognizerContext 对象

在应用程序的 WndProc 过程中,当启动时收到WM_CREATE消息时,将创建使用默认识别器的新识别器上下文。 此上下文用于应用程序中的所有识别。

case WM_CREATE:
{
    HRESULT hr;
    hr = CoCreateInstance(CLSID_InkRecognizerContext,
             NULL, CLSCTX_INPROC_SERVER, IID_IInkRecognizerContext,
             (void **) &g_pIInkRecoContext);
    if (FAILED(hr))
    {
        ::MessageBox(NULL, TEXT("There are no handwriting recognizers installed.\n"
            "You need to have at least one in order to run this sample.\nExiting."),
            gc_szAppName, MB_ICONERROR);
        return -1;
    }
  //...

识别笔划

当用户单击“识别!” 菜单项来访问更新。 该代码从 InkDisp 对象) 获取指向 inkStrokes (pIInkStrokes 墨迹指针,然后使用调用 putref_Strokes 将 InkStrokes 传递到识别器上下文。

 case WM_COMMAND:
  //...
  else if (wParam == ID_RECOGNIZE)
  {
      // change cursor to the system's Hourglass
      HCURSOR hCursor = ::SetCursor(::LoadCursor(NULL, IDC_WAIT));
      // Get a pointer to the ink stroke collection
      // This collection is a snapshot of the entire ink object
      IInkStrokes* pIInkStrokes = NULL;
      HRESULT hr = g_pIInkDisp->get_Strokes(&pIInkStrokes);
      if (SUCCEEDED(hr)) 
      {
          // Pass the stroke collection to the recognizer context
          hr = g_pIInkRecoContext->putref_Strokes(pIInkStrokes);
          if (SUCCEEDED(hr)) 
          {

然后,代码调用 InkRecognizerContext 对象的 Recognize 方法,并传入指向 IInkRecognitionResult 对象的指针来保存结果。

              // Recognize
              IInkRecognitionResult* pIInkRecoResult = NULL;
              hr = g_pIInkRecoContext->Recognize(&pIInkRecoResult);
              if (SUCCEEDED(hr)) 
              {

最后,代码使用 IInkRecognitionResult 对象的 TopString 属性将排名靠前的识别结果检索到字符串变量中,释放 IInkRecognitionResult 对象,并在消息框中显示字符串。

                  // Get the best result of the recognition 
                  BSTR bstrBestResult = NULL;
                  hr = pIInkRecoResult->get_TopString(&bstrBestResult);
                  pIInkRecoResult->Release();
                  pIInkRecoResult = NULL;

                  // Show the result string
                  if (SUCCEEDED(hr) && bstrBestResult)
                  {
                      MessageBoxW(hwnd, bstrBestResult, 
                                  L"Recognition Results", MB_OK);
                      SysFreeString(bstrBestResult);
                  }  }
        

请确保在用法之间重置识别器上下文。

              // Reset the recognizer context
              g_pIInkRecoContext->putref_Strokes(NULL);
          }
          pIInkStrokes->Release();
      }
      // restore the cursor
      ::SetCursor(hCursor);
  }