如何在WinForm中实现输入时可旋转90度的垂直文本框?
WinForm 垂直文本框实现方案
实现思路
- 原生TextBox控件不支持直接旋转绘制,因此采用自定义控件的方式实现,继承
Control基类避免原生绘制逻辑干扰 - 内部维护
_inputText(存储输入的文本内容)、_cursorIndex(存储光标当前位置)两个核心状态变量 - 重写
OnPaint方法:通过Graphics.RotateTransform实现文本90度旋转绘制,同时绘制竖状输入光标 - 重写键盘输入事件:处理字符输入、退格删除、方向键光标移动逻辑
- 可选添加
Timer控件控制光标闪烁效果,更贴近原生输入体验
核心实现代码
public class VerticalTextBox : Control { private string _inputText = string.Empty; private int _cursorIndex = 0; private bool _cursorVisible = true; private readonly Timer _cursorTimer; public VerticalTextBox() { DoubleBuffered = true; // 光标闪烁定时器,间隔500ms _cursorTimer = new Timer { Interval = 500 }; _cursorTimer.Tick += (s, e) => { _cursorVisible = !_cursorVisible; Invalidate(); }; _cursorTimer.Start(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics g = e.Graphics; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.Clear(BackColor); // 坐标系转换,实现90度旋转,可调整角度适配顺时针/逆时针旋转需求 g.TranslateTransform(Width, 0); g.RotateTransform(90); // 绘制文本,关闭自动换行 using StringFormat sf = new StringFormat { FormatFlags = StringFormatFlags.NoWrap }; g.DrawString(_inputText, Font, new SolidBrush(ForeColor), 0, 0, sf); // 绘制光标 if (Focused && _cursorVisible) { float cursorX = g.MeasureString(_inputText[.._cursorIndex], Font, new PointF(0,0), sf).Width; g.DrawLine(Pens.Black, cursorX, 2, cursorX, Font.Height + 2); } } protected override void OnKeyPress(KeyPressEventArgs e) { base.OnKeyPress(e); if (char.IsControl(e.KeyChar)) { // 处理退格 if (e.KeyChar == (char)8 && _cursorIndex > 0) { _inputText = _inputText.Remove(_cursorIndex - 1, 1); _cursorIndex--; Invalidate(); } return; } // 插入输入字符 _inputText = _inputText.Insert(_cursorIndex, e.KeyChar.ToString()); _cursorIndex++; Invalidate(); } protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); // 左方向键:光标左移(对应垂直文本向上移动) if (e.KeyCode == Keys.Left && _cursorIndex > 0) { _cursorIndex--; Invalidate(); } // 右方向键:光标右移(对应垂直文本向下移动) else if (e.KeyCode == Keys.Right && _cursorIndex < _inputText.Length) { _cursorIndex++; Invalidate(); } } protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); _cursorTimer.Start(); } protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); _cursorTimer.Stop(); _cursorVisible = false; Invalidate(); } }
使用说明
- 编译项目后,该自定义控件会自动出现在工具箱中,直接拖拽到窗体即可使用
- 如果需要调整旋转方向,修改
RotateTransform的参数为-90即可适配不同的垂直排版需求 - 可通过修改控件的
Font、ForeColor、BackColor属性调整文本样式,和原生控件使用逻辑一致
内容的提问来源于stack exchange,提问作者Fame th
相关产品推荐
相关产品推荐

