Winform 实现成功、警告、错误、信息提示弹窗

Winform 实现成功、警告、错误、信息提示弹窗

  1. 设置窗体基础属性和控件位置

首先建立一个名为FmMessageAlert的窗体,设置其背景(BackColor)为白色,设置StartPosition=FormStartPosition.CenterScreen,设置大小为263, 163,在窗体顶部放上容器名为plTitle,此容器上放按钮名为btnClose,在下发放图片控件名为pbIcon,如下:

Winform 实现成功、警告、错误、信息提示弹窗_第1张图片
  1. 画窗体边框

重新OnPaint方法,代码如下:

 /*
以下为字段
*/
 private const int maxWidth = 480;

private Color startColor = Color.Lime; // 渐变填充起始色
private Color endColor = Color.Blue; // 渐变填充结束颜色
private Color cancelColor = Color.FromArgb(144, 147, 153);
private float angle = 45f;// 渐变填充绘制角度
MessageAlertButtons messageBoxButtons;
MessageAlertIcon messageBoxIcon;
private Color iconColor;
private string _text;
private string _caption;
private Bitmap bitmap;
private Button btnOk;
private Button btnCancel;

protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

            // 画外围边框
            using Pen pen = new Pen(iconColor, 1f);
            Rectangle boder = new Rectangle(0, 0, ClientRectangle.Width - 1, ClientRectangle.Height - 1);
            e.Graphics.DrawRectangle(pen, boder);
        }
  1. 给plTitle容器加上鼠标拖动事件

 private Point _point;
private void plTitle_MouseDown(object sender, MouseEventArgs e)
{
    _point = e.Location;
}

private void plTitle_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
        this.Location = new Point(this.Location.X + e.X - _point.X, this.Location.Y + e.Y - _point.Y);
}
  1. 给关闭按钮btnClose添加鼠标点击事件

private void btnClose_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.Cancel;
        this.Close();
    }
  1. 窗体构造器

public FmMessageAlert(string text, string caption, MessageAlertButtons buttons, MessageAlertIcon icon)
    {
        InitializeComponent();
        _text = text;
        _caption = caption;
        messageBoxButtons = buttons;
        messageBoxIcon = icon;
        SelectIcon(icon);
        BindData();
    }
  1. 两个枚举

 public enum MessageAlertButtons
    {
        //
        // 摘要:
        //     The message box contains an OK button.
        OK = 0,
        //
        // 摘要:
        //     The message box contains OK and Cancel buttons.
        OKCancel = 1,
    }

 public enum MessageAlertIcon
    {
        Success,
        Error,
        Warning,
        Information,
    }
  1. BindData方法,绑定控件颜色及生成按钮

private void BindData()
        {
            lblTitle.Text = _caption;
            rtbContent.Text = _text;
            plTitle.BackColor = iconColor;
            btnClose.BackColor = Color.Transparent;
            btnClose.ForeColor = Color.White;
            btnClose.Cursor = Cursors.Hand;
            btnClose.FlatStyle = FlatStyle.Flat;
            btnClose.FlatAppearance.BorderSize = 0;
            btnClose.FlatAppearance.MouseOverBackColor = iconColor.ChangeColor(0.3f);
            btnClose.FlatAppearance.MouseDownBackColor = iconColor.ChangeColor(-0.3f);

            switch (messageBoxButtons)
            {
                case MessageAlertButtons.OK:
                    btnOk = new Button();
                    btnOk.Text = "确定";
                    btnOk.BackColor = iconColor;
                    btnOk.ForeColor = Color.White;
                    btnOk.Cursor = Cursors.Hand;
                    btnOk.FlatStyle = FlatStyle.Flat;
                    btnOk.FlatAppearance.BorderSize = 0;
                    btnOk.FlatAppearance.MouseOverBackColor = iconColor.ChangeColor(0.3f);
                    btnOk.FlatAppearance.MouseDownBackColor = iconColor.ChangeColor(-0.3f);
                    btnOk.Location = new Point(81, 122);
                    btnOk.Size = new Size(100, 35);
                    btnOk.Click += btnConfirm_Click;
                    this.Controls.Add(btnOk);
                    break;

                default:
                    btnOk = new Button();
                    btnOk.Text = "确定";
                    btnOk.BackColor = iconColor;
                    btnOk.ForeColor = Color.White;
                    btnOk.Cursor = Cursors.Hand;
                    btnOk.FlatStyle = FlatStyle.Flat;
                    btnOk.FlatAppearance.BorderSize = 0;
                    btnOk.FlatAppearance.MouseOverBackColor = iconColor.ChangeColor(0.3f);
                    btnOk.FlatAppearance.MouseDownBackColor = iconColor.ChangeColor(-0.3f);
                    btnOk.Location = new Point(29, 122);
                    btnOk.Size = new Size(100, 35);
                    btnOk.Click += btnConfirm_Click;
                    this.Controls.Add(btnOk);
                    btnCancel = new Button();
                    btnCancel.Text = "取消";
                    btnCancel.BackColor = cancelColor;
                    btnCancel.ForeColor = Color.White;
                    btnCancel.Cursor = Cursors.Hand;
                    btnCancel.FlatStyle = FlatStyle.Flat;
                    btnCancel.FlatAppearance.BorderSize = 0;
                    btnCancel.FlatAppearance.MouseOverBackColor = cancelColor.ChangeColor(0.3f);
                    btnCancel.FlatAppearance.MouseDownBackColor = cancelColor.ChangeColor(-0.3f);
                    btnCancel.Location = new Point(134, 122);
                    btnCancel.Size = new Size(100, 35);
                    btnCancel.Click += btnCancel_Click;
                    this.Controls.Add(btnCancel);
                    break;
            }


            pbIcon.Image = bitmap;


        }
  1. 自动调整控件位置(此方法一定要放在窗体Load事件中)

 const int unitWidth = 10;
        private void Resize()
        {
            int w1 = lblTitle.Width, w2 = rtbContent.Width, h = rtbContent.Height;
            while (btnClose.Location.X - lblTitle.Location.X - lblTitle.Width < 5 && this.Width <= maxWidth)
            {
                rtbContent.AutoAdjustWidth(unitWidth, rtbContent.Width + unitWidth);
                this.Width += unitWidth;
                AdjustPosition();
                this.plTitle.Width += unitWidth;
                this.btnClose.Location = new Point(this.btnClose.Location.X + unitWidth, this.btnClose.Location.Y);
            }
            int n = _caption.Length;
            while (lblTitle.Width > 432)
            {
                lblTitle.Text = _caption[0..--n] + "...";
            }
            while (rtbContent.IsVerticalScrollBarVisible() && this.Width <= maxWidth)
            {
                //rtbContent.AutoAdjustWidth(unitWidth,rtbContent.Width + unitWidth);
                rtbContent.Width += unitWidth;
                this.Width += unitWidth;
                AdjustPosition();
                this.plTitle.Width += unitWidth;
                this.btnClose.Location = new Point(this.btnClose.Location.X + unitWidth, this.btnClose.Location.Y);
            }
            int maxw = w1;
            if (w1 < w2)
                maxw = w2;

            rtbContent.AutoAdjustHigh();
            if (rtbContent.Height >= 65)
            {
                int h1 = rtbContent.Height - 65;
                this.Height += h1;
                this.btnOk.Location = new Point(this.btnOk.Location.X, this.rtbContent.Location.Y + this.rtbContent.Height + 6);
                if (btnCancel != null)
                {
                    this.btnCancel.Location = new Point(this.btnCancel.Location.X, this.btnOk.Location.Y);
                }
                
            }
        }
        /// 
        /// 调整按钮位置
        /// 
        private void AdjustPosition()
        {
            if (btnCancel != null)
            {
                int w = (this.Width - this.btnOk.Width - btnCancel.Width - 6) >> 1;
                this.btnOk.Location = new Point(w, this.btnOk.Location.Y);
                this.btnCancel.Location = new Point(w + 100 + 6, this.btnCancel.Location.Y);
            }
            else
            {
                this.btnOk.Location = new Point((this.Width - this.btnOk.Width) >> 1, this.btnOk.Location.Y);
            }
        }
  1. 选择图标和颜色

 private void SelectIcon(MessageAlertIcon icon)
        {
            switch (icon)
            {
                case MessageAlertIcon.Error:
                    iconColor = Color.FromArgb(245, 108, 108);
                    bitmap = Properties.Resources.error;
                    break;
                case MessageAlertIcon.Warning:
                    iconColor = Color.FromArgb(230, 162, 60);
                    bitmap = Properties.Resources.waring;
                    break;
                case MessageAlertIcon.Success:
                    iconColor = Color.FromArgb(103, 194, 58);
                    bitmap = Properties.Resources.success;
                    break;
                default:
                    iconColor = Color.FromArgb(64, 158, 255);
                    bitmap = Properties.Resources.infomation_circle;
                    break;
            }
        }
  1. 颜色扩展

public static class ColorEx
    {
        /*
         * 加深:correctionFactor<0

            变亮:correctionFactor>0

            -1.0f <= correctionFactor <= 1.0f
         */
        public static Color ChangeColor(this Color color, float correctionFactor)
        {
            float red = (float)color.R;
            float green = (float)color.G;
            float blue = (float)color.B;

            if (correctionFactor < 0)
            {
                correctionFactor = 1 + correctionFactor;
                red *= correctionFactor;
                green *= correctionFactor;
                blue *= correctionFactor;
            }
            else
            {
                red = (255 - red) * correctionFactor + red;
                green = (255 - green) * correctionFactor + green;
                blue = (255 - blue) * correctionFactor + blue;
            }

            if (red < 0) red = 0;

            if (red > 255) red = 255;

            if (green < 0) green = 0;

            if (green > 255) green = 255;

            if (blue < 0) blue = 0;

            if (blue > 255) blue = 255;
            return Color.FromArgb(color.A, (int)red, (int)green, (int)blue);
        }
    }
  1. RichTextBox扩展

 public static class RichTextBoxEx
    {
        private const int WS_HSCROLL = 0x100000;
        private const int WS_VSCROLL = 0x200000;
        private const int GWL_STYLE = (-16);

        [System.Runtime.InteropServices.DllImport("user32", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        private static extern int GetWindowLong(IntPtr hwnd, int nIndex);

        ///        
        /// 判断是否出现垂直滚动条       
        ///       
        /// 待测控件      
        ///  出现垂直滚动条返回true,否则为false
        public static bool IsVerticalScrollBarVisible(this Control ctrl)
        {
            if (!ctrl.IsHandleCreated)
                return false;

            return (GetWindowLong(ctrl.Handle, GWL_STYLE) & WS_VSCROLL) != 0;
        }
        ///       
        /// 判断是否出现水平滚动条       
        ///        
        /// 待测控件       
        /// 出现水平滚动条返回true,否则为false
        public static bool IsHorizontalScrollBarVisible(this Control ctrl) 
        { 
            if (!ctrl.IsHandleCreated) 
                return false; 
            return (GetWindowLong(ctrl.Handle, GWL_STYLE) & WS_HSCROLL) != 0; 
        }
        /// 
        /// 自动调整高度
        /// 
        /// 
        /// 每次调整最小高度
        /// 最大高度,0和负数表示没有高度限制
        public static void AutoAdjustHigh(this Control ctrl,int high=24,int maxHigh=-1)
        {
            if(ctrl.IsVerticalScrollBarVisible())
            {
                int h=ctrl.Height;
                h += high;
                if (maxHigh > 0 && h > maxHigh)
                    return;
                ctrl.Height = h;
                ctrl.AutoAdjustHigh(high);
            }
        }
        /// 
        /// 自动调整宽度
        /// 
        /// 
        /// 每次调整最小宽度
        /// 最大宽度,-0和负数表示没有宽度限制
        public static void AutoAdjustWidth(this Control ctrl, int width = 10, int maxWidth = -1)
        {
            if (ctrl.IsHorizontalScrollBarVisible())
            {
                int w = ctrl.Width;
                w += width;
                if (maxWidth > 0 && w > maxWidth)
                    return;
                ctrl.Width = w ;
                ctrl.AutoAdjustWidth(width);
            }
        }
    }

提示窗体所有代码:

 public partial class FmMessageAlert : Form
    {
        private const int maxWidth = 480;

        private Color startColor = Color.Lime; // 渐变填充起始色
        private Color endColor = Color.Blue; // 渐变填充结束颜色
        private Color cancelColor = Color.FromArgb(144, 147, 153);
        private float angle = 45f;// 渐变填充绘制角度
        MessageAlertButtons messageBoxButtons;
        MessageAlertIcon messageBoxIcon;
        private Color iconColor;
        private string _text;
        private string _caption;
        private Bitmap bitmap;
        private Button btnOk;
        private Button btnCancel;
        public FmMessageAlert(string text, string caption, MessageAlertButtons buttons, MessageAlertIcon icon)
        {
            InitializeComponent();
            _text = text;
            _caption = caption;
            messageBoxButtons = buttons;
            messageBoxIcon = icon;
            SelectIcon(icon);
            BindData();
        }
        private void BindData()
        {
            lblTitle.Text = _caption;
            rtbContent.Text = _text;
            plTitle.BackColor = iconColor;
            btnClose.BackColor = Color.Transparent;
            btnClose.ForeColor = Color.White;
            btnClose.Cursor = Cursors.Hand;
            btnClose.FlatStyle = FlatStyle.Flat;
            btnClose.FlatAppearance.BorderSize = 0;
            btnClose.FlatAppearance.MouseOverBackColor = iconColor.ChangeColor(0.3f);
            btnClose.FlatAppearance.MouseDownBackColor = iconColor.ChangeColor(-0.3f);

            switch (messageBoxButtons)
            {
                case MessageAlertButtons.OK:
                    btnOk = new Button();
                    btnOk.Text = "确定";
                    btnOk.BackColor = iconColor;
                    btnOk.ForeColor = Color.White;
                    btnOk.Cursor = Cursors.Hand;
                    btnOk.FlatStyle = FlatStyle.Flat;
                    btnOk.FlatAppearance.BorderSize = 0;
                    btnOk.FlatAppearance.MouseOverBackColor = iconColor.ChangeColor(0.3f);
                    btnOk.FlatAppearance.MouseDownBackColor = iconColor.ChangeColor(-0.3f);
                    btnOk.Location = new Point(81, 122);
                    btnOk.Size = new Size(100, 35);
                    btnOk.Click += btnConfirm_Click;
                    this.Controls.Add(btnOk);
                    break;

                default:
                    btnOk = new Button();
                    btnOk.Text = "确定";
                    btnOk.BackColor = iconColor;
                    btnOk.ForeColor = Color.White;
                    btnOk.Cursor = Cursors.Hand;
                    btnOk.FlatStyle = FlatStyle.Flat;
                    btnOk.FlatAppearance.BorderSize = 0;
                    btnOk.FlatAppearance.MouseOverBackColor = iconColor.ChangeColor(0.3f);
                    btnOk.FlatAppearance.MouseDownBackColor = iconColor.ChangeColor(-0.3f);
                    btnOk.Location = new Point(29, 122);
                    btnOk.Size = new Size(100, 35);
                    btnOk.Click += btnConfirm_Click;
                    this.Controls.Add(btnOk);
                    btnCancel = new Button();
                    btnCancel.Text = "取消";
                    btnCancel.BackColor = cancelColor;
                    btnCancel.ForeColor = Color.White;
                    btnCancel.Cursor = Cursors.Hand;
                    btnCancel.FlatStyle = FlatStyle.Flat;
                    btnCancel.FlatAppearance.BorderSize = 0;
                    btnCancel.FlatAppearance.MouseOverBackColor = cancelColor.ChangeColor(0.3f);
                    btnCancel.FlatAppearance.MouseDownBackColor = cancelColor.ChangeColor(-0.3f);
                    btnCancel.Location = new Point(134, 122);
                    btnCancel.Size = new Size(100, 35);
                    btnCancel.Click += btnCancel_Click;
                    this.Controls.Add(btnCancel);
                    break;
            }


            pbIcon.Image = bitmap;


        }
        const int unitWidth = 10;
        private void Resize()
        {
            int w1 = lblTitle.Width, w2 = rtbContent.Width, h = rtbContent.Height;
            while (btnClose.Location.X - lblTitle.Location.X - lblTitle.Width < 5 && this.Width <= maxWidth)
            {
                rtbContent.AutoAdjustWidth(unitWidth, rtbContent.Width + unitWidth);
                this.Width += unitWidth;
                AdjustPosition();
                this.plTitle.Width += unitWidth;
                this.btnClose.Location = new Point(this.btnClose.Location.X + unitWidth, this.btnClose.Location.Y);
            }
            int n = _caption.Length;
            while (lblTitle.Width > 432)
            {
                lblTitle.Text = _caption[0..--n] + "...";
            }
            while (rtbContent.IsVerticalScrollBarVisible() && this.Width <= maxWidth)
            {
                //rtbContent.AutoAdjustWidth(unitWidth,rtbContent.Width + unitWidth);
                rtbContent.Width += unitWidth;
                this.Width += unitWidth;
                AdjustPosition();
                this.plTitle.Width += unitWidth;
                this.btnClose.Location = new Point(this.btnClose.Location.X + unitWidth, this.btnClose.Location.Y);
            }
            int maxw = w1;
            if (w1 < w2)
                maxw = w2;

            rtbContent.AutoAdjustHigh();
            if (rtbContent.Height >= 65)
            {
                int h1 = rtbContent.Height - 65;
                this.Height += h1;
                this.btnOk.Location = new Point(this.btnOk.Location.X, this.rtbContent.Location.Y + this.rtbContent.Height + 6);
                if (btnCancel != null)
                {
                    this.btnCancel.Location = new Point(this.btnCancel.Location.X, this.btnOk.Location.Y);
                }
                
            }
        }
        /// 
        /// 调整按钮位置
        /// 
        private void AdjustPosition()
        {
            if (btnCancel != null)
            {
                int w = (this.Width - this.btnOk.Width - btnCancel.Width - 6) >> 1;
                this.btnOk.Location = new Point(w, this.btnOk.Location.Y);
                this.btnCancel.Location = new Point(w + 100 + 6, this.btnCancel.Location.Y);
            }
            else
            {
                this.btnOk.Location = new Point((this.Width - this.btnOk.Width) >> 1, this.btnOk.Location.Y);
            }
        }
        private void SelectIcon(MessageAlertIcon icon)
        {
            switch (icon)
            {
                case MessageAlertIcon.Error:
                    iconColor = Color.FromArgb(245, 108, 108);
                    bitmap = Properties.Resources.error;
                    break;
                case MessageAlertIcon.Warning:
                    iconColor = Color.FromArgb(230, 162, 60);
                    bitmap = Properties.Resources.waring;
                    break;
                case MessageAlertIcon.Success:
                    iconColor = Color.FromArgb(103, 194, 58);
                    bitmap = Properties.Resources.success;
                    break;
                default:
                    iconColor = Color.FromArgb(64, 158, 255);
                    bitmap = Properties.Resources.infomation_circle;
                    break;
            }
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

            // 画外围边框
            using Pen pen = new Pen(iconColor, 1f);
            Rectangle boder = new Rectangle(0, 0, ClientRectangle.Width - 1, ClientRectangle.Height - 1);
            e.Graphics.DrawRectangle(pen, boder);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void FmMessageAlert_FormClosing(object sender, FormClosingEventArgs e)
        {
            bitmap.Dispose();
            btnOk.Dispose();
            btnCancel?.Dispose();
            btnClose.Dispose();
            this.Dispose();
        }
        /// 
        /// 确认
        /// 
        /// 
        /// 
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
        private void FmMessageAlert_Load(object sender, EventArgs e)
        {
            Resize();

        }
        private Point _point;
        private void plTitle_MouseDown(object sender, MouseEventArgs e)
        {
            _point = e.Location;
        }

        private void plTitle_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
                this.Location = new Point(this.Location.X + e.X - _point.X, this.Location.Y + e.Y - _point.Y);
        }
    }

为其加上扩展方法

/// 
    /// 弹窗提示扩展
    /// 
    public static class MessageAlertEx
    {
        /// 
        /// 弹窗提示扩展
        /// 
        /// 提示内容
        /// 标题
        /// 按钮(目前只实现Ok、OkCancel)
        /// 图标(目前只实现Success、Error、Warning、Information)
        /// 返回DialogResult结果
        public static DialogResult ShowAlert(string text, string caption, MessageAlertButtons buttons, MessageAlertIcon icon)
        {
            using FmMessageAlert userMessageAlertControl = new FmMessageAlert(text, caption, buttons, icon);
            return userMessageAlertControl.ShowDialog();
        }
        public static DialogResult ShowAlert(string text, string caption)
        {
            return ShowAlert(text, caption, MessageAlertButtons.OK, MessageAlertIcon.Information);
        }
        public static DialogResult ShowAlert(this Form form, string text, string caption, MessageAlertButtons buttons, MessageAlertIcon icon)
        {
            return ShowAlert(text, caption, buttons, icon);
        }
        public static DialogResult ShowAlert(this Form form, string text, string caption)
        {
            return ShowAlert(text, caption);
        }
    }

在窗体中使用

 this.ShowAlert("成功", "提示", MessageAlertButtons.OK, Common.MessageAlertIcon.Success);

this.ShowAlert("失败", "提示", MessageAlertButtons.OK, Common.MessageAlertIcon.Error);
// 或者
MessageAlertEx.ShowAlert("失败", "提示", MessageAlertButtons.OK, Common.MessageAlertIcon.Error);

效果

Winform 实现成功、警告、错误、信息提示弹窗_第2张图片
Winform 实现成功、警告、错误、信息提示弹窗_第3张图片
Winform 实现成功、警告、错误、信息提示弹窗_第4张图片
Winform 实现成功、警告、错误、信息提示弹窗_第5张图片
Winform 实现成功、警告、错误、信息提示弹窗_第6张图片

你可能感兴趣的:(c#)