简体   繁体   English

如何在Edit Control MFC中获取光标位置?

[英]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++. 注意:我正在用C ++实现逻辑。

Reading the documentation makes this quite easy. 阅读文档使此操作非常容易。 You will use GetCaretPos() and CharFromPos() in conjunction. 您将结合使用GetCaretPos()CharFromPos()

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: 如文档中所述,可以使用CEdit :: ReplaceSel来执行此操作:

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 : 如果您希望在当前有选择的情况下在当前光标位置插入文本,则可以通过调用CEdit :: SetSel来删除选择而无需更改当前光标位置:

m_edit.SetSel(-1, 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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