用颜色填充面板的一部分

时间:2014-05-07 14:45:45

标签: c# winforms controls

我正试图获得一种错误解析器窗口。它是一个包含在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;
}

它只是在面板底部绘制小矩形。它不会表现出来。

1 个答案:

答案 0 :(得分:0)

调用base.OnPaint()在更改绘制选项之前... base.OnPaint()将删除您对该对象所做的任何修改,因为它期望从scractch开始,因此会消除您之前所做的操作。 ..