获取离光标最近的字符索引问题
问题一;
在编辑控件内,希望获取离光标最近的字符索引,
pEditExpr为编辑控件指针
方法一:
CPoint CursorPos;
::GetCursorPos(&CursorPos);
pEditExpr->ScreenToClient(&CursorPos);
int n=pEditExpr->CharFromPos(CursorPos);
int nCharIndex=LOWORD(n);
方法二:
///获取光标所删除的字符//////////
CPoint CaretPos; //光标位置,屏幕坐标
if(!::GetCaretPos(&CaretPos)) return FALSE;
int n= pEditExpr ->CharFromPos(CaretPos);
int nCharIndex=LOWORD(n);
编辑控件内的字符串: fhlwtyox
方法一执行的结果总是获取了 最后一个字符索引, 即x, 方法二正确.
我不明白的是: 应该是获取光标位置(屏幕坐标), 而后转换为编辑控件窗口的客户区坐标才是正确的, 为什么是获取添加号(caret)的位置呢?
问题二;
pEditExpr->ScreenToClient(&CursorPos);
使用ScreenToClient是不是将坐标原点(屏幕左上角(包括菜单和工具栏))转换到编辑控件窗口左上角.
如果是, 我也可以自己转换,代码如下
CRect EditRect;
pEditExpr->GetWindowRect(&EditRect);
CPoint LeftUpofEdit(EditRect.Left, EditRect.top); //获取编辑控件左上角的屏幕坐标
现在完成可以将问题一中的CPoint CursorPos; //光标位置
::GetCursorPos(&CursorPos);
这样可从屏幕坐标转换编辑控件窗口客户区坐标:
CPoint ClientCursorPos;
ClientCursorPos= CursorPos- LeftUpofEdit;