Vb.Net: Limit the total width of characters entered into a textbox? -


let me clear - not looking static character limit here (textbox.maxlength doesn't cut it.)

i'm making simple messaging program , i'd implement character limit. messages displayed inside listbox , can't horizontally scrolled/wrapped. solution: impose limit on every message users don't accidentally cut off own messages.

the problem 10 small characters lot smaller 10 full width characters. - e.g. , w:

  • iiiiiiiiii

  • wwwwwwwwww

i'd find way limit characters entered text box actual amount of pixels string wide. that:

  • nobody can use capitals , cut off, ,
  • nobody can type , stopped character limit far earlier neccesary.

for reference, i'm using verdana 8.25pt listbox.

any suggestions appreciated, thanks.

this should trick you. i've deliberately chosen keyup event because user see letter typed , disappearing.

private sub textbox1_textchanged(sender object, e keyeventargs) handles textbox1.keyup     dim text1 string = textbox1.text     dim textboxfont font = textbox1.font     dim textsize size = textrenderer.measuretext(text1, textboxfont)     if textsize.width > textbox1.clientrectangle.width         dim cursorlocation integer = textbox1.selectionstart         textbox1.text = textbox1.text.remove(cursorlocation - 1, 1)         if cursorlocation > textbox1.text.length             textbox1.selectionstart = textbox1.text.length         else             textbox1.selectionstart = cursorlocation         end if     end if end sub 

basically happening text rendered (not displayed) using font of textbox , measured. if width of rendered text greater client area of textbox, letter removed @ point typed. can anywhere in text box.

if cursor @ end of text when letter removed, .net automatically sets cursor position beginning letter removed. sub checks if initial cursor position bigger index length of new textbox contents. if so, cursor set end again. otherwise moved 1 because character deleted.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -