【问题标题】:.NET Winforms Vertical Progress Bar Text.NET Winforms 垂直进度条文本
【发布时间】:2023-04-02 18:59:01
【问题描述】:

最近,我的 win 表单应用程序需要一个垂直进度条。派生类如下所示。我还需要在进度条上添加文本。由于透明度问题,它上面的标签不起作用。经过一番研究,我发现了一些东西。但问题是,虽然进度条是垂直的,但它上面的文本却是水平的。我也需要垂直的。我该怎么做?

谢谢。

public class VProgressBar : ProgressBar
{
    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.Style |= 0x04;

            if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6)
            {
                cp.ExStyle |= 0x02000000; // WS_EX_COMPOSITED 
            }

            return cp;
        }
    }

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == 0x000F)
        {
            using (Graphics graphics = CreateGraphics())
            using (SolidBrush brush = new SolidBrush(ForeColor))
            {
                SizeF textSize = graphics.MeasureString(Text, Font);
                graphics.DrawString(Text, Font, brush, (Width - textSize.Width) / 2, (Height - textSize.Height) / 2);
            }
        }
    }

    [EditorBrowsable(EditorBrowsableState.Always)]
    [Browsable(true)]
    public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {
            base.Text = value;
            Refresh();
        }
    }

    [EditorBrowsable(EditorBrowsableState.Always)]
    [Browsable(true)]
    public override Font Font
    {
        get
        {
            return base.Font;
        }
        set
        {
            base.Font = value;
            Refresh();
        }
    }
}

【问题讨论】:

标签: c# .net winforms wndproc createparams


【解决方案1】:

您需要使用StringFormat 使用标志垂直绘制字符串。在您的 WndProc 方法中尝试以下操作:

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == 0x000F)
        {
            using (Graphics graphics = CreateGraphics())
            using (SolidBrush brush = new SolidBrush(ForeColor))
            {
                StringFormat format = new StringFormat(
                       StringFormatFlags.DirectionVertical);

                SizeF textSize = graphics.MeasureString(Text, Font);
                graphics.DrawString(
                     Text, Font, brush, 
                     (Width / 2 - textSize.Height / 2),
                     (Height / 2 - textSize.Width / 2),
                     format);
            }
        }
    }

【讨论】:

  • 谢谢丹尼尔,它成功了。我还需要使用 graphics.RotateTransform(180) 从下到上显示文本。
猜你喜欢
  • 1970-01-01
  • 2010-11-20
  • 2016-07-07
  • 2010-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-21
  • 2011-10-23
相关资源
最近更新 更多