简体   繁体   中英

How to get cursor position in Edit Control MFC?

Is there any way to know the current cursor position in the Edit Control?

I have a scenario where I need to insert text in the current cursor position.

Note: I'm implementing the logic in C++.

Reading the documentation makes this quite easy. You will use GetCaretPos() and CharFromPos() in conjunction.

return m_edit.CharFromPos(m_edit.GetCaretPos());

You don't strictly need to query for the cursor position, if you want to insert text at the current location. The CEdit::ReplaceSel can be used to do that, as explained in the documentation:

If there is no current selection, the replacement text is inserted at the current cursor location.

Depending on your specific requirements you would have to deal with the case, when there is a non-empty selection. The most natural implementation would be to replace the current selection. That's what users expect, and you wouldn't need to implement any additional code logic.

If you would rather insert text at the current cursor location in case there currently is a selection, you can remove the selection without altering the current cursor position by calling CEdit::SetSel :

m_edit.SetSel(-1, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM