.net - Making a WinForms TextBox behave like your browser's address bar -
when c# winforms textbox receives focus, want behave browser's address bar.
to see mean, click in web browser's address bar. you'll notice following behavior:
- clicking in textbox should select text if textbox wasn't focused.
- mouse down , drag in textbox should select text i've highlighted mouse.
- if textbox focused, clicking not select text.
- focusing textbox programmatically or via keyboard tabbing should select text.
i want in winforms.
fastest gun alert: please read following before answering! guys. :-)
calling .selectall() during .enter or .gotfocus events won't work because if user clicked textbox, caret placed clicked, deselecting text.
calling .selectall() during .click event won't work because user won't able select text mouse; .selectall() call keep overwriting user's text selection.
calling begininvoke((action)textbox.selectall) on focus/enter event enter doesn't work because breaks rule #2 above, keep overriding user's selection on focus.
first of all, answers! 9 total answers. thank you.
bad news: of answers had quirks or didn't work quite right (or @ all). i've added comment each of posts.
good news: i've found way make work. solution pretty straightforward , seems work in scenarios (mousing down, selecting text, tabbing focus, etc.)
bool alreadyfocused; ... textbox1.gotfocus += textbox1_gotfocus; textbox1.mouseup += textbox1_mouseup; textbox1.leave += textbox1_leave; ... void textbox1_leave(object sender, eventargs e) { alreadyfocused = false; } void textbox1_gotfocus(object sender, eventargs e) { // select text if mouse isn't down. // makes tabbing textbox give focus. if (mousebuttons == mousebuttons.none) { this.textbox1.selectall(); alreadyfocused = true; } } void textbox1_mouseup(object sender, mouseeventargs e) { // web browsers google chrome select text on mouse up. // if textbox isn't focused, // , if user hasn't selected text. if (!alreadyfocused && this.textbox1.selectionlength == 0) { alreadyfocused = true; this.textbox1.selectall(); } }
as far can tell, causes textbox behave web browser's address bar.
hopefully helps next guy tries solve deceptively simple problem.
thanks again, guys, answers helped lead me towards correct path.
Comments
Post a Comment