C# Label自适应,自动换行案例

  项目中用到了消息对话框,类似于Messagebox,然后我就自定义了个Messagebox,其中用到了label自适应,自动换行,先看效果图吧。

C# Label自适应,自动换行案例_第1张图片

 

按照下面步骤来来

   1  新建一个Form为BasicDialog,form里添加一个label,BasicDialog大小为(440,240)

    2  label的autosize为true,MaximumSize为(420,0), 让MaximumSize略小于BasicDialog的Width

    BasicDialog的代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; 

namespace CentralProject.CentralForm
{
  
     
    public partial class BasicDialog : Form
    { 
        
        public string Msg = "";

        public DialogType DType = DialogType.None;

        public BasicDialog()
        {
            InitializeComponent();
        }

        private void BasicDialog_Load(object sender, EventArgs e)
        {
            Text = StaticModel.Language.Get_Tip();

            lbMsg.Text = Msg;

            //文字内容太小时,就居中显示,Form高度适中就可以
            if (lbMsg.Height < 50)
            {
                lbMsg.Location = new Point((this.Width - lbMsg.Width) / 2, 20);
                lbMsg.TextAlign = ContentAlignment.MiddleCenter;
                this.Height = 160;
            }
            else
            {
                this.Height = lbMsg.Height + 100;
                lbMsg.TextAlign = ContentAlignment.MiddleLeft;
            }
        }

        public DialogType ShowForm()
        {
            this.ShowDialog();
            return DType;
        }
         
    }
}

   3 再新建Form为 OKForm,在OKForm里添加一个按钮,且OKForm继承BasicDialog

     按钮的Anchor设置为Bottom, Left, Right即可

    C# Label自适应,自动换行案例_第2张图片

  OKForm代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; 

namespace CentralProject.CentralForm
{
    public partial class OKForm : BasicDialog
    {
        public OKForm(string msg)
        {
            InitializeComponent();
            Msg = msg;
        }

        private void OKForm_Load(object sender, EventArgs e)
        {
           
        }
         
        private void btn_ok_Click(object sender, EventArgs e)
        {
            DType = DialogType.Yes;
            this.Close();
        }
    }
}

  4 调用OKForm

   new CentralForm.OKForm("已经完成了").ShowForm();

 说明: Yes/No , Yes/No/Cancel,的按钮设置同OKForm的按钮一样

 

 

 

 

 

你可能感兴趣的:(C#自定义控件,C#,开发总结)