.NET Winforms垂直进度条文本

时间:2012-12-12 11:48:54

标签: c# .net winforms wndproc createparams

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

感谢。

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();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要使用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);
            }
        }
    }