13
votes

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

3 Answers

17
votes

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
9
votes

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.

0
votes

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.