继承Label的重绘事件以实现竖排显示文字(含实例原码)


最近因为一个任务要竖排显示英文,如果微软的东西能像word一样直接可以设置属性竖排显示那该有多好啊!

可惜就是这么个简单的问题害我搞了半天。

其实最重要的是:继承后的控件OnPaint事件好像失效了,必须要在WndProc(ref Message m)中做绘制工作,而在OnPaint事件中不做事或根据条件选择性做事。

但至于为什么继承后控件的OnPaint事件会失效,我还没搞清楚原因,因为这不太符合常理。如果哪位大侠知道,还请不啬赐教!

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace Earnest
{
    public class LabelExt : Label
    {
        public LabelExt() : base()
        {
        }

        public const Int32 WM_PAINT = 0xF;

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m); // 这里会转到OnPaint事件

            // 处理绘制消息
            if (m.Msg == WM_PAINT)
            {
                if (竖排显示)
                {
                    Graphics g = this.CreateGraphics();
                    StringFormat strFormat = new StringFormat(StringFormatFlags.DirectionVertical);
                    RectangleF rectF = new RectangleF(0, 0, this.Width, this.Height);
                    g.DrawString(this.Text, this.Font, Brushes.Black, rectF, strFormat);
                    g.Dispose();
                }
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            if (横排显示)
            {
                base.OnPaint(e);
            }
            //else 留空:让控件不处理原绘制
        }
    }
}


注意:外部代码中应调整好要显示的Label的大小,否则可能只显示一部分文字。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值