用颜色填充面板的一部分

本文关键字:一部分 颜色 填充 | 更新日期: 2023-09-27 18:02:15

我正在尝试获得一种错误解析器窗口。它是一个包含在Windows窗体中的面板。我使用FillRectangle方法在面板中绘制一个小矩形,但是当我编译并使用它时,它不会显示。

下面是我的代码:
public enum NotificationPanelState
{
    None            = 0,
    Error           = 1,
    Warning         = 2,
    Information     = 3,
    Popup           = 4,
}
private NotificationPanelState state = new NotificationPanelState();
public NotificationPanelState PanelState
{
    get { return state; }
    set { state = value; this.Invalidate(); }
}
public NotificationPanel()
{
    SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint
        | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer, true);
    this.Size = new Size(200, 50);
    this.MaximumSize = new Size(200, 50);
    this.MinimumSize = new Size(200, 50);
    this.BackColor = Color.FromArgb(20, 20, 20);
}
protected override void OnPaint(PaintEventArgs e)
{
    e.Graphics.Clear(BackColor);

    Rectangle stateRect = new Rectangle(
        new Point(this.Size.Width - 10, this.Size.Height),
        new Size(this.Size.Width, 5));
    switch (PanelState)
    {
        case NotificationPanelState.None:
            e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(40, 40, 40)),
                stateRect);
            break;
        case NotificationPanelState.Error:
            e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(255, 0, 0)),
                stateRect);
            break;
        case NotificationPanelState.Warning:
            e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(250, 200, 0)),
                stateRect);
            break;
        case NotificationPanelState.Popup:
            e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(0, 0, 0)),
                stateRect);
            break;
        case NotificationPanelState.Information:
            e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(0, 142, 250)),
                stateRect);
            break;
        default:
            e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(20, 20, 20)),
                stateRect);
            break;
    }
    //Draws error string
    e.Graphics.DrawString(ErrorMessage, StringFont, Brushes.Black,
        new Point(this.Size.Width / 2, (this.Size.Height / 2) - 10), 
        new StringFormat { 
            Trimming = StringTrimming.EllipsisCharacter, 
            Alignment = StringAlignment.Center 
        });
    base.OnPaint(e);
}

我一定是做了什么蠢事…

我是这样使用它的:

private void Main_Load(object sender, EventArgs e)
{
    notificationPanel1.PanelState = NotificationPanelState.Error;
    notificationPanel1.ErrorMessage = "ERROR 403 FORBIDDEN";
    notificationPanel1.StringFont = new Font("Segoe UI", 10, FontStyle.Bold);
    notificationPanel1.ForeColor = Color.Gainsboro;
}

它只是面板底部的小矩形的绘图。不显示

用颜色填充面板的一部分

在更改绘制选项之前调用base.OnPaint()…base.OnPaint()将删除你对对象所做的任何修改,因为它期望从头开始,因此将清除你之前所做的…