onChar中文乱码问题的解决方法

void CTestView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
 // TODO: 在此添加消息处理程序代码和/或调用默认值
 CWindowDC dc(this);
 CFont font;
 font.CreatePointFont(300,L"微软雅黑",NULL);
 CFont *pOldFont = dc.SelectObject(&font);
 TEXTMETRIC tm;
 dc.GetTextMetrics(&tm);
 if (0x0d == nChar)
 {
  m_strline.Empty();
  m_ptOrigin.y += tm.tmHeight;
 }
 else if (0x08 == nChar)
 {
  COLORREF cls = dc.SetTextColor(dc.GetBkColor());
  dc.TextOutW(m_ptOrigin.x,m_ptOrigin.y,m_strline);
  m_strline = m_strline.Left(m_strline.GetLength() - 1);
  dc.SetTextColor(cls);
 }
 else
 {
  m_strline += (WCHAR)nChar;
 }
 CSize sz = dc.GetTextExtent(m_strline);
 CPoint pt;
 pt.x = m_ptOrigin.x + sz.cx;
 pt.y = m_ptOrigin.y;
 SetCaretPos(pt);
 dc.TextOutW(m_ptOrigin.x,m_ptOrigin.y,m_strline);
 dc.SelectObject(pOldFont);
 CView::OnChar(nChar, nRepCnt, nFlags);
}

把m_string+=(char)nChar

改成m_string+=(WCHAR)nChar; 就可以了,因为汉字是双字

The WCHAR data type contains a 16-bit Unicode character

你可能感兴趣的:(String,null,character,微软)