bebo
bebo

Reputation: 839

Windows Forms Textbox: Selection and Caret position

After setting the SelectionStart and SelectionLength, the Caret is at the end of the selection.

How can I move the Caret to the beginning of the selection?


I now tried this: The question is not answered by the other threads

SelectionStart = selStart;  // set the desired position
SelectionLength = 0;
MyLibs.WindowsDll.POINT point;
MyLibs.WindowsDll.GetCaretPos(out point); // save the position
SelectionLength = restOfWord.Length;      // extend the selection
MyLibs.WindowsDll.SetCaretPos(point.X, point.Y);  // restore caret position

GetCaretPos and SetCaretPos are working somehow, but not as it should. Using the above code snippet, the caret is indeed blinking at the beginning of the selection.

But ... then I hit backspace or cursor left/right, the caret still behaves like it is still at the end of the selection.

Upvotes: 2

Views: 934

Answers (1)

Dmitry Kazakov
Dmitry Kazakov

Reputation: 1669

Unfortunately, you can not do this using managed code like C#, but to achieve this goal you may use C++, SetFocus() function, for example:

//use SetFocus()
pEdit->SetFocus()
//place caret at the end:
pEdit->SendMessage (WM_KEYDOWN,VK_END,0);
//simulate keyup:
m_Edit->SendMessage (WM_KEYUP,VK_END,0);
//send the key code:
m_Edit->SendMessage(WM_CHAR,'A',0);

Have a look to MSDN: https://msdn.microsoft.com/en-us/library/windows/desktop/ms646312(v=vs.85).aspx

You may use also CEdit::SetSel to accomplish that:

CEdit* e = (CEdit*)GetDlgItem(IDC_EDIT1);
e->SetFocus();
e->SetSel(0,-1); // move cursor at the end
e->SetSel(-1); // remove selection

See details in Stackoverflow question: CEdit control MFC, placing cursor to end of string after SetWindowText

UPDATED:

If you need to set position to the beginning you can reset the Caret position to start before displaying the text using:

SetSel (0,0);

You can not move the caret to the beginning while keeping the text selected using basic C#/C++ functions, however you can override basic "Caret" logic using C++ or/and Assembler.

Upvotes: -1

Related Questions