473,326 Members | 2,104 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

TextBox vertical text alignment (Windows Forms)

7
I need to align text to the bottom of a multiline TextBox in Windows Forms - can't figure out how!

In WPF you can set the VerticalContentAlignment property, easy answer, but it looks like there is no such property in Windows Forms TextBox!

But I have seen it done many times in Windows Forms-based apps and I wonder how do they do it?
Sep 13 '09 #1
10 37564
cloud255
427 Expert 256MB
Hmmm, I couldn't get this right either, the closest I got to getting this right is to add a label to the textbox, set the label's parent to the textbox and set label's dockstyle to bottom. Maybe someone else has a better solution for the OP?
Sep 13 '09 #2
GaryTexmo
1,501 Expert 1GB
Ahhh, my brain refuses to process the problem apparently. Can you provide like a mockup or a mspaint image presenting what you what?

Thanks, and sorry for my denseness :)
Sep 13 '09 #3
alextj
7
What can be archived with this is a terminal-like application, where you type commands on the bottom of the window and the text scrolls from the bottom towards the top.
Here is a screenshot of my quick and dirty CAN (Control Area Network) console app made using WPF, which uses textBox.VerticalContentAlignment = VerticalAlignment.Top property:


This looks like it's a very simple and basic feature, but somehow it seems it's missing completely from Windows Forms.

Edit: I am not quite sure whether this forum image thing will work for everyone, so here's direct URL just in case:
Expand|Select|Wrap|Line Numbers
  1. http://img410.imageshack.us/img410/5440/textboxvalign.jpg
Sep 13 '09 #4
GaryTexmo
1,501 Expert 1GB
Oh ok cool, thanks. I thought that might have been what you meant, but I wasn't sure. I don't have time tonight so I'll take a look tomorrow.
Sep 14 '09 #5
GaryTexmo
1,501 Expert 1GB
I don't have an easy solution for you, unfortunately. I can't imagine why they have that functionality in WPF but not in .NET, it seems so useful! :)

That said, I do have something for you... whether or not you want to use it over Cloud's solution is up to you. In your screenshot, it looks like you're not editing from the bottom up, just appending text to the text box that way. This makes life a little simpler... you just have to pad the text box with newline characters.

This is the code for a form with a text box and a rich textbox (named appropriately) on it.

Expand|Select|Wrap|Line Numbers
  1.     public partial class Form1 : Form
  2.     {
  3.         string rawText = "";
  4.  
  5.         public Form1()
  6.         {
  7.             InitializeComponent();
  8.         }
  9.  
  10.         private void textBox1_KeyDown(object sender, KeyEventArgs e)
  11.         {
  12.             if (e.KeyCode == Keys.Return)
  13.             {
  14.                 if (rawText != "") rawText += Environment.NewLine + textBox1.Text;
  15.                 else rawText = textBox1.Text;
  16.                 textBox1.Text = "";
  17.  
  18.                 Graphics g = richTextBox2.CreateGraphics();
  19.                 SizeF singleLine = g.MeasureString("blah", richTextBox2.Font);
  20.                 SizeF strSize = g.MeasureString(rawText, richTextBox2.Font);
  21.  
  22.                 // copy to the display RTB
  23.                 richTextBox2.Clear();
  24.  
  25.                 string[] lines = rawText.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
  26.                 float textHeight = lines.Length * singleLine.Height;
  27.                 float leftoverHeight = richTextBox2.Height - textHeight;
  28.  
  29.                 float pad = (float)Math.Ceiling(leftoverHeight / (double)singleLine.Height);
  30.  
  31.                 for (int i = 0; i < pad; i++)
  32.                     richTextBox2.AppendText(Environment.NewLine);
  33.                 richTextBox2.AppendText(rawText);
  34.                 richTextBox2.ScrollToCaret();
  35.             }
  36.         }
  37.     }
Remember, this is just a rough test I did, which seems to work... you can clean it up a bit better if you want to use it. Also, you'd need to do something when the text box is resized because as it is, it doesn't realign itself when you change it.

I hope that helped.
Sep 14 '09 #6
alextj
7
Hi Gary, I've checked your code and wrote my own version here - it seems like a working hack - but hack it is indeed.

This one has an input TextBox - the one where you type into and an output TextBox - the multiline TextBox which shows terminal output with the scrolling text. I use an ordinary multiline TextBox here.

This version handles resizing too, by calling AlignTextToBottom() and ScrollToBottom() on Form1 - Size Changed event.

Expand|Select|Wrap|Line Numbers
  1. private void textBoxInput_KeyUp(object sender, KeyEventArgs e) {
  2.     if (e.KeyCode == Keys.Enter) {
  3.         textBoxOutput.AppendText(Environment.NewLine + textBoxInput.Text);
  4.         textBoxOutput_AlignTextToBottom();
  5.         textBoxOutput_ScrollToBottom();
  6.         textBoxInput.Clear();
  7.     }
  8. }
  9. private void textBoxOutput_AlignTextToBottom() {
  10.     int visibleLines = (int)(textBoxOutput.Height / textBoxOutput.Font.GetHeight())-1;
  11.     if (visibleLines > textBoxOutput.Lines.Length) {
  12.         int emptyLines = (visibleLines - textBoxOutput.Lines.Length);
  13.         for (int i = 0; i < emptyLines; i++) {
  14.             textBoxOutput.Text = (Environment.NewLine + textBoxOutput.Text);
  15.         }
  16.     }
  17. }
  18. private void textBoxOutput_ScrollToBottom() {
  19.     textBoxOutput.SelectionStart = textBoxOutput.Text.Length;
  20.     textBoxOutput.ScrollToCaret();
  21. }
  22. private void Form1_SizeChanged(object sender, EventArgs e) {
  23.     textBoxOutput_AlignTextToBottom();
  24.     textBoxOutput_ScrollToBottom();
  25. }
I guess there are a few things that should be optimized here... The crazy amount of string operations at the time when the scroll buffer gets large enough is what's scaring me (I come from embedded software world - I'm clueless here).

At the end I don't know how much resources this is gonna save compared to a WPF based application. It seems to consume less memory looking in Task Manager, but things will change once I add CAN interface. And what about CPU time?

This is the first time I'm doing Windows app programming, so I'm quite new to the tools and haven't yet looked into how you guys measure performance here.

Anyway thanks again for your replies, cloud and Gary :)
Sep 14 '09 #7
GaryTexmo
1,501 Expert 1GB
I agree it feels like a hack, but at the same time I'm not sure how else you'd do it. I mean, if I were to do this kind of thing in a console style program, I'd be taking pretty much the exact same approach :)

That said, in terms of optimization, you actually shouldn't have much to worry about. Worst case scenario is when you have one line of text that needs to be pushed to the bottom of the text box. As you add more lines you actually add less padding, to the point where you aren't adding any.

As for what it saves you over a WPF application, unfortunately I don't know anything about WPF so I can't really offer any insight there.
Sep 14 '09 #8
alextj
7
Yeah, that's true about the worst case scenario.

Actually, it adds padding only one time - at the first line of input. After that it already has the needed number of line breaks that fill the entire thing, so there is no more need to add anything after that.

Only when if you resize the window to be large enough, it will start adding more line fillers. But that, of course, only counts when the window is large enough to fit the entire text.

So yeah, you're right - I guess there's need to worry about it too much :)

Ahh - the bliss of the community - I wouldn't get this right without your help. Hope this topic helps someone with the same problem some day ;)
Sep 14 '09 #9
cloud255
427 Expert 256MB
@alextj
Well, I've also started delving into WPF over the last few months, in my experience it is far more resource intensive than winforms. But this is the direction that MS is taking .Net so maybe creating your application in WPF would give it a longer lifetime and I suppose the sooner all us .Net people get used to XAML the better...

Do remember that your core C# code will remain unchanged; WPF is just a technology for fancy UIs.
Sep 14 '09 #10
alextj
7
@cloud255
I just gave this another though and realized that if label is used for output text - then the text cannot be selected, which is sometimes a needed feature. Add to that the fact that there is no vertical scrolling to view the history - and it makes it a pretty poor terminal application.

But if label text could be made selectable and a vertical scrollbar added - this solution would be a winner. I guess we can think of something to add the scrollbar, but what about selectable label text? Possible?
Sep 14 '09 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Richard Lionheart | last post by:
Hi All, I tried creating a C# Form using Petzold's "Programming MS Windows with C#" guidance. He recommended using the namespace System.Windows.Forms. However, VS.NET claims "the type or...
3
by: Rvo | last post by:
I have a userform which contains a textbox (System.Windows.forms.textbox) with multiline set to True. This box contains a certain number of characters which reach below the bottom of the box....
2
by: John Smith | last post by:
Hi all; Putting "Due" into the column header of a datagrid. Font is a proportional fort. When the alignment is left, there is some space between the column separator bar and the D in Due....
3
by: Simon Abolnar | last post by:
Is it possible to align headers and text in different way. Because with: dgts.GridColumnStyles(0).Alignment = HorizontalAlignment.Center alignment is set for all column (header and text). ...
0
by: VorTechS | last post by:
I'm having a problem with an inherited label, applying text rotation to aligned text. If text rotation is applied to the aligned text, the alignment goes 'nuts'. I can find no logic to what is...
15
by: Matthew | last post by:
Hi, I'm mainly a coder, PHP at the moment, but from time to time need to design and use some css. I've a css text alignment issue. Mostly to align text neatly in the past I've used tables....
2
by: RSH | last post by:
I have been experimenting with overriding the Paint event on Win Form controls...more specifically trying to force the text to render as Antialiased text. I have not been successful in any of the...
1
by: aagarwal8 | last post by:
Hi, My requirement is to display anit-aliased text across my application. The technique that MSDN provides for rendering anti-aliased text, can be used when drawing individual text strings....
21
by: Dan Tallent | last post by:
In my application I have a form (Customer) that I want to be able to open multiple copies at once. Within this form I have other forms that can be opened. Example: ZipCode. When the user enters...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.