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 secondthis.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 colorg.Clear(this.BackColor);// Draw the countdowng.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);