16,472
社区成员
发帖
与我相关
我的任务
分享
int CMainWindow::GetNearestPosPart(const CPoint point, CDC *pDc)
{
CString string = m_strInputText;
int nLen = (pDc->GetTextExtent(string, string.GetLength() / 2)).cx + m_ptTextOrigin.x;
int nIndex = string.GetLength() / 2;
while(string.GetLength() > 1)//必须用大于1而不能用不等于1,否则会死循环
{
if(point.x == nLen)
return nIndex;
else if(point.x < nLen)
{
string = string.Left(nIndex);
nLen -= (pDc->GetTextExtent(string, string.GetLength() / 2)).cx;
nIndex -= string.GetLength() / 2;
}
else
{
string = string.Right(string.GetLength() - nIndex);
nLen += (pDc->GetTextExtent(string, string.GetLength() / 2)).cx;
nIndex += string.GetLength() / 2;
}
}
int nCurLen = (pDc->GetTextExtent(m_strInputText, nIndex)).cx + m_ptTextOrigin.x;//获取字符串到光标点所在字符的长度
int nPreLen = (pDc->GetTextExtent(m_strInputText, nIndex - 1)).cx + m_ptTextOrigin.x;//获取字符串到光标点所在字符的前一个字符的长度
CString str;
str.Format(TEXT("(%d, %d)——%d, %d, %d"), point.x, point.y, nIndex, m_strInputText.GetLength(), nLen);//问题所在
pDc->TextOutW(32, 2 * m_nyChar + 16, str);
pDc->TextOutW(202, 2 * m_nyChar + 16, m_strInputText);
return ((point.x - nPreLen < nCurLen - point.x ? (nIndex - 1) : nIndex));
}
int CMainWindow::GetNearestPos(const CPoint point)
{
if(point.x < m_ptTextOrigin.x)
return 0;
CClientDC dc(this);
int nLen = dc.GetTextExtent(m_strInputText).cx;
if(point.x > m_ptTextOrigin.x + nLen)
return nLen;
return GetNearestPosPart(point, &dc);
}
void CMainWindow::OnLButtonDown(UINT nFlags, CPoint point)
{
if(m_rcTextBox.PtInRect(point))
{
m_nTextPos = GetNearestPos(point);
PositionCaret();
}
}