自学内容网 自学内容网

C# GDI绘制的倒计时控件

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);


原文地址:https://blog.csdn.net/weixin_43050480/article/details/144277194

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!