CEdit control MFC, placing cursor to end of string

2019-04-20 02:01发布

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.

How can this be done?

3条回答
疯言疯语
2楼-- · 2019-04-20 02:35

You can use CEdit::SetSel to accomplish that:

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.

查看更多
手持菜刀,她持情操
3楼-- · 2019-04-20 02:42

You can use CEdit::SetSel to accomplish that.

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
查看更多
\"骚年 ilove
4楼-- · 2019-04-20 02:49

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.

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

  1. Add text to edit & call SetSel(-1)
  2. update static control

And the cursor would not stay in the end. But when I changed it to

  1. update static control
  2. Add text to edit & call 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.

查看更多
登录 后发表回答