如何让我的 Ellipse 在 C# 上使用 Timer.Interval 闪烁? (紧急红灯模拟)(在 Ubuntu 上使用 MonoDevelop)

How to get my Ellipse to flash with Timer.Interval on C#? (Emergency Red Light Simulation) (Using MonoDevelop on Ubuntu)

我不知道如何让我的代码上的红灯按照我为其设置的时间间隔闪烁。

我试过使用 Invalidate 和 Update,以及 Refresh,其中 none 似乎有效。我对 C# 和一般编码还很陌生,所以代码可能存在严重缺陷,如果是这种情况,请不要犹豫对我大喊大叫。

public class UI: Form
{
    protected Label lights_title = new Label();
    protected Button pause, resume, exit;
    protected bool isPaint = true;
    public static System.Timers.Timer g_shock = new System.Timers.Timer();

    public UI()
    {
        // text initialization
        this.Text = "Chukwudi's Flashing Red Light";
        this.lights_title.Text = "Ikem's Emergency Lights!";
        // size initialization - determine the size of the UI Form
        this.lights_title.Size = new Size(700, 40);
        this.Size = new Size(1920, 1080);

        // location initialization (x,y) x pulls you right as the number increase, y pulls you down
        this.lights_title.Location = new Point(598, 60);

        // title config & background color
        this.lights_title.BackColor = Color.Coral;
        this.lights_title.TextAlign = (System.Drawing.ContentAlignment)HorizontalAlignment.Center;

        this.BackColor = Color.DimGray;

        Render();

        g_shock.Enabled = false;
        g_shock.Elapsed += ManageOnPaint;
        g_shock.Enabled = true;
        g_shock.Start();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        Graphics shape = e.Graphics;
        if (isPaint)
        {
            shape.FillRectangle(Brushes.Black, new Rectangle(598, 90, 700, 700));
            shape.FillEllipse(Brushes.Red, new Rectangle(650, 140, 600, 600));
        }
        shape.FillRectangle(Brushes.Brown, new Rectangle(598, 785, 700, 60));
    }

    protected void ManageOnPaint(object sender, System.Timers.ElapsedEventArgs elapsed)
    {
        g_shock.Interval = 1000;
        Invalidate();
        Update();
        // turn something to true
    }
}

正如 Alex F 所指出的,您并不是在切换某些东西来跟踪控件是否为红色。 而且您没有在 timereventhandler 中绘制任何内容。 我的建议如下,我省略了与我的观点无关的部分。

private bool isRed;
private static System.Timers.Timer g_shock = new System.Timers.Timer();

public UI()
{
    g_shock.Elapsed += ManageOnPaint;
    g_shock.Interval = 1000;
    g_shock.Start();
}

private void ManageOnPaint(object sender, System.Timers.ElapsedEventArgs elapsed)
{
    if (isRed)
    {
        // Set ellipse color non red            
    }
    if (!isRed)
    {
        // Set ellipse color red
    }

    // Toggle isRed
    isRed = !isRed;
}

protected override void OnPaint(PaintEventArgs e)
{
    /// paint ellipse with current ellipse color
}