【问题标题】:How to make textbox rotated 90 (vertical) during typing?如何在打字过程中使文本框旋转 90(垂直)?
【发布时间】:2021-11-01 17:30:44
【问题描述】:

我需要制作一个像 excel 这样的垂直文本框。打字光标显示为垂直,如果我输入一些文本,文本将从上到下延伸。并且文本旋转了 90 度。(不溢出线)

如何在WinForm中创建垂直文本框?

【问题讨论】:

  • 不可能。虽然您可以在键入时自行绘制文本,但用户将无法执行常规编辑操作,例如使用鼠标进行选择和视觉反馈。最好在属性编辑器中使用 TextBox 输入字段来伪造它。

标签: c# .net vb.net winforms textbox


【解决方案1】:

你的问题让我很好奇!所以我试图实现一些东西。事实证明,在winforms 中做起来有点复杂……

这是我的镜头,你需要改进它,但它有效(ish)。想法是画一个白色背景来隐藏TextBox绘制的文字,然后垂直绘制。

结果:

请注意,您可以使用另一种绘制文本的方法来改进结果 - this code for example

代码:

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

public class VerticalTextBox : TextBox
{
    private bool bFlip = true;

    public VerticalTextBox() 
    {
        Multiline = true;
        SetStyle(ControlStyles.UserPaint, true);
        TextChanged += OnTextChanged;
    }

    private void OnTextChanged(object sender, EventArgs eventArgs) 
    {
        Invalidate(); // repaint all
    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {
        var g = e.Graphics;
        g.FillRectangle(new SolidBrush(BackColor), ClientRectangle);

        var stringFormat = new StringFormat {
            Alignment = StringAlignment.Center,
            Trimming = StringTrimming.None,
            FormatFlags = StringFormatFlags.DirectionVertical
        };

        Brush textBrush = new SolidBrush(ForeColor);

        var storedState = g.Transform;

        if (bFlip)
        {
            g.RotateTransform(180f);
            g.TranslateTransform(-ClientRectangle.Width,-ClientRectangle.Height);  
        }
        g.DrawString(
            Text,
            Font,
            textBrush,
            ClientRectangle,
            stringFormat);

        g.Transform = storedState;
    }



    [Description("When this parameter is true the VLabel flips at 180 degrees."),Category("Appearance")]
    public bool Flip180
    {
        get => bFlip;
        set
        {
            bFlip = value;
            Invalidate();
        }
    }
}

参考文献

  1. VerticalLabel

  2. SetStyle 告诉 TextBox 调用 Paint 事件。

更好的(?)替代品

  1. 为了获得更好的结果,在winforms中,我建议你了解FastColoredTextBox并使用它。

  2. 迁移到 WPF,apparently is easy

【讨论】:

    猜你喜欢
    • 2016-05-05
    • 2011-03-10
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    相关资源
    最近更新 更多