- 使用 TextBxRender.DrawTextBox 繪製 TextBox
- 直接新增 ComboBox 並把 TextFormatFlags 放進去當成選項
- 使用 ComboBox 選擇 TextFormatFlags 來變化、觀察 TextBox 內文字效果
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace TextBoxRendererSample
{
public class CustomTextBox : Control
{
private TextFormatFlags _textFlags = TextFormatFlags.EndEllipsis;
private ComboBox _comboBox = new ComboBox();
private Rectangle _textBorder = new Rectangle();
private Rectangle _textRectangle = new Rectangle();
public CustomTextBox() : base()
{
this.Location = new Point(10, 10);
this.Size = new Size(300, 200);
this.Font = SystemFonts.IconTitleFont;
TextBoxInit();
ComboBoxInit();
}
private void TextBoxInit()
{
_textBorder.Location = new Point(10, 10);
_textBorder.Size = new Size(200, 50);
_textRectangle.Location = new Point(_textBorder.X + 2, _textBorder.Y + 2);
_textRectangle.Size = new Size(_textBorder.Size.Width - 4, _textBorder.Height - 4);
}
private void ComboBoxInit()
{
_comboBox.Location = new Point(10, 100);
_comboBox.Size = new Size(150, 20);
_comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
// 把 TextFormatFlags Enum 塞進 ComboBox 內去
_comboBox.Items.AddRange(Enum.GetNames(typeof(TextFormatFlags)).ToArray());
_comboBox.SelectedIndex = _comboBox.FindStringExact(nameof(TextFormatFlags.EndEllipsis));
_comboBox.SelectionChangeCommitted += ComboBox_SelectionChangeCommitted;
this.Controls.Add(_comboBox);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// TextBoxRenderer class can be used to draw a text box with visual styles.
if (TextBoxRenderer.IsSupported)
{
this.Parent.Text = "CustomTextBox Enabled";
this.Text = "This is a long sentence that will exceed the text box bounds";
// 繪製 TextBox 重點
TextBoxRenderer.DrawTextBox(
e.Graphics,
_textBorder,
this.Text,
this.Font,
_textRectangle,
_textFlags,
TextBoxState.Normal);
}
else
{
this.Parent.Text = "CustomTextBox Disabled";
}
}
private void ComboBox_SelectionChangeCommitted(object sender, EventArgs e)
{
if (Enum.TryParse(_comboBox.Text, out TextFormatFlags flags) == false)
return;
this._textFlags = flags;
Invalidate();
}
}
}
TextFormatFlags.EndEllipsis 效果:文字碰上 TextBox 邊界,會以 ... 來表示截斷文字
沒有留言:
張貼留言