Setting Alignment in TextBoxes, or Through the Looking Glass


With a couple of exceptions, the UI controls provided by the .NET Compact Framework are thin wrappers around the controls provided by the operating system.  Perhaps I'm too sanguine, but I expect the basic controls (button, check box, radio button, edit control and list box) to have the same capabilities on both Windows and Windows CE.  For the most part, they do; however, there are occasions where the differences are just plain annoying.


I came across one of these this morning.  A customer needed a textbox that kept the text on a single line but allowed text alignment to be set.  The Windows CE textbox control only allows text to be left-aligned unless the control is multiline.  I don't know why, but there it is.  Since the  normal Compact Framework textbox is just a thin wrapper around the CE edit control, it met the first criteria, but failed the second.  Setting the textbox's Multiline property to true met the second criteria, but failed the first.  Or did it?


I noticed that the TextBox class has a property called AcceptReturn.  At first glance, this appeared to be just what I wanted.  However, I soon discovered that this property didn't allow me to supress line breaks: it determined whether the Enter key is sent to the textbox or the form's default button.  Back to the drawing board.


My next thought was to try eating the Enter key in the textbox's KeyPress, KeyDown or KeyUp event handlers.  I soon found that non-character keys do not trigger KeyPress events [see my next post for a revision].  And a quick test showed that though I could detect the Enter key in the KeyDown and KeyUp events, setting  the KeyEventArgs.Handled property to true didn't supress the line break.


In between yanking my hair out and beating my head on the wall, I stumbled across the Form.KeyPreview property.  When this property is set to true, all key events are sent to the form before being dispatched to a control.  By setting KeyEventArgs.Handled in the form's KeyUp event handler, I was able to suppress the Enter key and thus the line break.


This wasn't an obvious solution, so let me recap:

  1. To allow textbox alignment to be set, the textbox's Multiline property must be set to true.
  2. To keep the text on a single line in a multiline textbox:
    1. Set the form's KeyPreview property to true. This will route keys events to the form prior to sending them to the control.
    2. Add a handler for the form's KeyUp event. In this handler, disallow the enter key if the textbox has focus.

        private void Form1_KeyUp(object sender, KeyEventArgs e)


            if (this.textBox1.Focused && e.KeyCode == Keys.Enter)


                e.Handled = true;







[Edited 02/07/2007.  Added link to next article.]