|
How to select some text in textbox with cursor positioned before first character of selection? In other words i want to achieve the result of SHIFT+LeftArrow operation with code. P.S Setting caret position in TextBox is not the end result i want to achieve, actually i want to change the visible text. | | Broken Pipe Monday, July 06, 2009 12:32 PM | The native Window control doesn't support it. Faking the keystrokes is a very awkward workaround. "Changing visible text" should never be a problem, just assign the Text property. Or assign the SelectedText property to replace a selection.
Hans Passant. | | nobugz Monday, July 06, 2009 1:14 PM | I see... i guess i have to use what i have.... I have implemented custom auto-complete functional, when a suggestion is appended to textbox.text it is selected and if the string is long then user can't see text that he is typing, he always see the end of string in textbox. | | Broken Pipe Monday, July 06, 2009 1:31 PM | i think this will do what you want:
[DllImport
(
"user32.dll"
, CharSet =
CharSet
.Auto, SetLastError =
true
)]
private
static
extern bool SetCaretPos(int x, int y);
private void textBox1_TextChanged(object sender, EventArgs e) {
Point p=((TextBox)sender).GetPositionFromCharIndex(4);
((TextBox)sender).Select(4, 4);
SetCaretPos(p.X, p.Y);
}
- Marked As Answer byLinda LiuMSFT, ModeratorTuesday, July 07, 2009 8:24 AM
- Edited byazad_du_hunt Monday, July 06, 2009 2:03 PM
- Unmarked As Answer bynobugzMVP, ModeratorTuesday, July 07, 2009 8:30 AM
- Edited byazad_du_hunt Monday, July 06, 2009 2:00 PM
- Edited byazad_du_hunt Monday, July 06, 2009 2:02 PM
-
| | azad_du_hunt Monday, July 06, 2009 1:50 PM |
i think this will do what you want:
[DllImport ( "user32.dll" , CharSet = CharSet .Auto, SetLastError = true )] private static extern bool SetCaretPos( int x, int y); private void textBox1_TextChanged( object sender, EventArgs e) { Point p=(( TextBox )sender).GetPositionFromCharIndex(4); (( TextBox )sender).Select(4, 4); SetCaretPos(p.X, p.Y); }
It works, with TextBox, but it doesn't work with ComboBox, trying to make it work... (not just becouse Combobox doens't have GetPositionFromCharIndex) i'm tried with pixel coords - Edited byBroken Pipe Monday, July 06, 2009 3:30 PM
-
| | Broken Pipe Monday, July 06, 2009 3:17 PM | And it's just set caret visually, but logically caret stays where it were in textbox (new typed characters appear there) | | Broken Pipe Monday, July 06, 2009 3:34 PM | Yeah, don't mess with the caret. By far the easiest workaround is to simply make your text box wider. Making it smaller than the text it could contain just doesn't work very well.
Hans Passant. | | nobugz Monday, July 06, 2009 4:16 PM |
|