MFC简易文本编辑功能

1.创建插入符

afx_msg int CTextEditorDlg::OnCreate(LPCREATESTRUCT crect)
{
 TEXTMETRIC tm;
 CClientDC cdc(this);
 GetTextMetrics(cdc.m_hDC,&tm);
 CreateSolidCaret(tm.tmAveCharWidth/3,tm.tmHeight);
 SetCaretPos(m_CaretPit);
 ShowCaret();
 return 0;
}

2.鼠标单击改变插入符位置

afx_msg void CTextEditorDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
 m_InputStr = "";
 m_CaretPit.x = point.x;
 m_CaretPit.y = point.y;
 SetCaretPos(m_CaretPit);
}

3.键盘事件响应

afx_msg void CTextEditorDlg::OnKeyDown(UINT nchar, UINT nRepCnt, UINT nFlags)
{
 POINT tempp;
 CSize size;
 int interval = 'A' - 'a';
 CClientDC cdc(this);
 TEXTMETRIC tm;
 GetTextMetrics(cdc.m_hDC, &tm);
 unsigned  char  kbuf[256];
 GetKeyboardState(kbuf);
 int cap = kbuf[VK_CAPITAL] & 1;
 switch (nchar)
 {
 case VK_SHIFT:
  m_ShiftFlag = 1;
  break;
 case VK_RETURN:
  size = cdc.GetTextExtent(m_InputStr);
  m_CaretPit.x = m_CaretPit.x + size.cx;
  m_CaretPit.y = m_CaretPit.y + tm.tmHeight;
  SetCaretPos(m_CaretPit);
  m_InputStr = "";
  break;
 default:
 if ((m_ShiftFlag+cap)==1)
  m_InputStr += (TCHAR)nchar;
 else
  m_InputStr += (TCHAR)(nchar-interval);
 size = cdc.GetTextExtent(m_InputStr);
 tempp = m_CaretPit;
 tempp.x = m_CaretPit.x + size.cx;
 SetCaretPos(tempp);
 cdc.TextOutW(m_CaretPit.x, m_CaretPit.y, m_InputStr);
 break;
}
}
void CTextEditorDlg::OnKeyUp(UINT nchar, UINT nRepCnt, UINT nFlags)
{
 switch (nchar)
 {
 case VK_SHIFT:
  m_ShiftFlag = 0;
  break;
 }
}

你可能感兴趣的:(C++,#,MFC,文本编辑,插入符)