C# GDI绘制的倒计时控件

发布于:2024-12-06 ⋅ 阅读:(137) ⋅ 点赞:(0)

C# GDI绘制的倒计时控件

using System;
using System.Drawing;
using System.Windows.Forms;
 
public class CountdownControl : Control
{
    private Timer timer;
    private TimeSpan remainingTime;
 
    public CountdownControl()
    {
        this.timer = new Timer();
        this.timer.Interval = 1000; // 1 second
        this.timer.Tick += Timer_Tick;
        this.remainingTime = TimeSpan.FromMinutes(1); // Default countdown of 1 minute
    }
 
    private void Timer_Tick(object sender, EventArgs e)
    {
        if (remainingTime > TimeSpan.Zero)
        {
            remainingTime = remainingTime.Subtract(TimeSpan.FromSeconds(1));
        }
        else
        {
            timer.Stop();
        }
 
        this.Invalidate(); // Redraw the control
    }
 
    public void StartCountdown(TimeSpan duration)
    {
        remainingTime = duration;
        timer.Start();
    }
 
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        Graphics g = e.Graphics;
 
        // Clear the control with the background color
        g.Clear(this.BackColor);
 
        // Draw the countdown
        g.DrawString($"{remainingTime:mm\\:ss}", this.Font, Brushes.Black, new PointF(0, 0));
    }
}
 
// Usage example:
// CountdownControl countdown = new CountdownControl();
// countdown.StartCountdown(TimeSpan.FromMinutes(5)); // Start a 5 minute countdown
// this.Controls.Add(countdown);


网站公告

今日签到

点亮在社区的每一天
去签到