C++ CEdit 控件 MFC,将光标置于 SetWindowText 后的字符串末尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1480873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CEdit control MFC, placing cursor to end of string after SetWindowText
提问by Nick Dandoulakis
I am using VC9, I've a CEdit control whose contents are reset to default test (say - "fill-in") at the click of a button and then i call SetFocus for the CEdit control. The problem is that the cursor blinks at the start of the default text, and i want it to blink an the end of the default string.
我正在使用 VC9,我有一个 CEdit 控件,它的内容在单击一个按钮时被重置为默认测试(比如“填充”),然后我为 CEdit 控件调用 SetFocus。问题是光标在默认文本的开头闪烁,我希望它在默认字符串的末尾闪烁。
How can this be done?
如何才能做到这一点?
回答by Nick Dandoulakis
You can use CEdit::SetSelto accomplish that.
您可以使用CEdit::SetSel来实现这一点。
Example:
例子:
CEdit* e = (CEdit*)GetDlgItem(IDC_EDIT1);
e->SetWindowText("hello world");
e->SetFocus();
e->SetSel(0,-1); // select all text and move cursor at the end
e->SetSel(-1); // remove selection
回答by user3455965
You can use CEdit::SetSel
to accomplish that:
您可以使用它CEdit::SetSel
来实现:
CEdit* e = (CEdit*)GetDlgItem(IDC_EDIT1);
e->SetWindowText("hello world");
// e->SetSel(0,-1); // you don't need this line
e->SetFocus();
e->SetSel(-1);
It will place the cursor in the end of the string.
它将光标放在字符串的末尾。
回答by Gagan
I had a strange finding but still relevant to it. This solution did not work for me initially. Even after calling SetSel(-1)my cursor was moving to the top of the edit box. Then I did some code reshuffle and it started working.
我有一个奇怪的发现,但仍然与之相关。这个解决方案最初对我不起作用。即使在调用SetSel(-1) 之后,我的光标也在移动到编辑框的顶部。然后我做了一些代码改组,它开始工作了。
The learning was that if I update any other control after updating the edit control, the cursor will move to the top of the edit box. But if edit box is the last control updated, the cursor remains in the end of the edit box.
学到的是,如果我在更新编辑控件后更新任何其他控件,光标将移动到编辑框的顶部。但如果编辑框是最后更新的控件,则光标停留在编辑框的末尾。
Like I had a code something like
就像我有一个类似的代码
- Add text to edit & call SetSel(-1)
- update static control
- 添加文本以进行编辑并调用SetSel(-1)
- 更新静态控制
And the cursor would not stay in the end. But when I changed it to
并且光标不会停留在最后。但是当我把它改成
- update static control
- Add text to edit & call SetSel(-1)
- 更新静态控制
- 添加文本以进行编辑并调用SetSel(-1)
My cursor was displayed in the end of the edit box.
我的光标显示在编辑框的末尾。
I had it on my mind since the day I had this finding to update the knowledge base here. Hope it helps some random soul whose cursor jumps to top of edit box even after calling the API.
从我有这个发现来更新知识库的那一天起,我就一直在想。希望它可以帮助一些随机的灵魂,即使在调用 API 后,光标也会跳到编辑框的顶部。