Any expert here to guide me how to achieve this style of textbox as in the image below. Each characters are separated and precisely visible. This is a snapshot from an windows application. So i thought C#.Net winforms can achieve this.
-
2It is important to note that subclassing the TextBox or RichTextBox classes in .NET WinForms is not practical. They are just wrappers around the native Windows text-edit controls, and so you won't be able to do things you'd normally expect to be able to do, like overriding OnPaint and intercepting input, at least not without some complicated p/invoke and a WndProc override. Personally, I'd rather write a new TextBox from scratch than get involved trying to subclass the existing one. – Peter Duniho Oct 23 '14 at 00:07
1 Answers
It really depends on exactly what you want to do. If you want the user to be able to edit, then you might want to write a class that inherits TextBoxBase and correctly overrides all the appropriate features in that class. This is non-trivial.
However, if you just want to display the text, the code is actually quite simple:
using System.Drawing;
using System.Windows.Forms;
namespace <YourNameSpaceHere>
{
class TickLabel : Control
{
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
int x = 0;
int[] widths = _MeasureWidths(Text);
using (Pen pen = new Pen(ForeColor))
{
for (int i = 0; i < Text.Length; i++)
{
TextRenderer.DrawText(e.Graphics, Text.Substring(i, 1), Font, new Point(x, 0), ForeColor);
x += widths[i];
e.Graphics.DrawLine(pen, x, ClientSize.Height, x, ClientSize.Height - 10);
}
}
}
private int[] _MeasureWidths(string text)
{
int[] widths = new int[text.Length];
for (int i = 0; i < text.Length; i++)
{
widths[i] = TextRenderer.MeasureText(text.Substring(i, 1), Font, ClientSize, TextFormatFlags.NoPadding).Width;
}
return widths;
}
}
}
Here's a screenshot of the result:
Note that I have set the background color to yellow, docked the control inside a Panel
to provide the border, and have sized the Panel
's height so that the ticks wind up where I want. Without too much extra trouble you could add an auto-sizing behavior to the control, as well as for it to support a border directly. Also, I used a hard-coded height for the ticks, but you might find it looks better if you scale the ticks according to the font size and/or control height.
I used the default Designer-selected font, but a fixed-space font might look better and suit your needs better.
If you do wind up going the editable-text route, the above should still give you some idea of the basic technique. It may require a fair amount of experimentation to get something that looks and works "just right" to you.

- 68,759
- 7
- 102
- 136