Dit moi quel endroit de ce script je doit modifier pour que les bips s'arretent quand je clique "OK" sur la fenetre qui me prévient que le temps est écoulé. :
using System; using System.Drawing; using System.Windows.Forms; using System.IO; using System.Media;
public class CookTimerForm : Form { private Label timeLabel; private Button[] quickButtons; private NumericUpDown hoursInput, minutesInput, secondsInput; private Button setButton, startStopButton, testSoundButton; private ComboBox soundComboBox; private TrackBar volumeTrackBar; private Label volumeValueLabel; private CheckBox alwaysOnTopCheckBox;
private System.Windows.Forms.Timer countdownTimer;
private int remainingSeconds = 0;
private bool isTimerRunning = false;
private SoundPlayer alarmPlayer;
private string[] soundNames = new string[] {
"Bip classique (440Hz)",
"Bip aigu (880Hz)",
"Bip grave (220Hz)",
"Double bip (440/880Hz)",
"Alarme montante",
"Alarme sirène"
};
public CookTimerForm()
{
InitializeComponents();
alarmPlayer = new SoundPlayer();
}
private void InitializeComponents()
{
this.Text = "Cook Timer";
this.ClientSize = new Size(430, 260);
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.StartPosition = FormStartPosition.CenterScreen;
// Time Label
timeLabel = new Label
{
Text = "00:00:00",
Font = new Font("Helvetica", 32, FontStyle.Bold),
TextAlign = ContentAlignment.MiddleCenter,
Location = new Point(10, 10),
Size = new Size(this.ClientSize.Width - 20, 50),
ForeColor = Color.DarkBlue
};
this.Controls.Add(timeLabel);
// Quick Buttons
int[] quickTimes = { 3, 5, 10, 15, 20, 30 };
quickButtons = new Button[quickTimes.Length];
for (int i = 0; i < quickTimes.Length; i++)
{
quickButtons[i] = new Button
{
Text = $"{quickTimes[i]} min",
Location = new Point(10 + (i % 3) * 70, 70 + (i / 3) * 30),
Size = new Size(65, 25),
Tag = quickTimes[i] * 60,
BackColor = Color.LightBlue,
FlatStyle = FlatStyle.Flat
};
quickButtons[i].Click += QuickButton_Click;
this.Controls.Add(quickButtons[i]);
}
// Custom Time Inputs
Label hLabel = new Label { Text = "H:", Location = new Point(220, 70), Size = new Size(20, 20) };
hoursInput = new NumericUpDown { Minimum = 0, Maximum = 23, Location = new Point(240, 70), Size = new Size(40, 20), Value = 0 };
Label mLabel = new Label { Text = "M:", Location = new Point(285, 70), Size = new Size(20, 20) };
minutesInput = new NumericUpDown { Minimum = 0, Maximum = 59, Location = new Point(305, 70), Size = new Size(40, 20), Value = 0 };
Label sLabel = new Label { Text = "S:", Location = new Point(350, 70), Size = new Size(20, 20) };
secondsInput = new NumericUpDown { Minimum = 0, Maximum = 59, Location = new Point(370, 70), Size = new Size(40, 20), Value = 0 };
this.Controls.AddRange(new Control[] { hLabel, hoursInput, mLabel, minutesInput, sLabel, secondsInput });
setButton = new Button
{
Text = "Définir",
Location = new Point(220, 95),
Size = new Size(190, 25),
BackColor = Color.LightGreen,
FlatStyle = FlatStyle.Flat
};
setButton.Click += SetButton_Click;
this.Controls.Add(setButton);
// Start/Stop Button
startStopButton = new Button
{
Text = "Démarrer",
Location = new Point(10, 130),
Size = new Size(200, 30),
BackColor = Color.LightGreen,
FlatStyle = FlatStyle.Flat,
Font = new Font("Arial", 10, FontStyle.Bold)
};
startStopButton.Click += StartStopButton_Click;
this.Controls.Add(startStopButton);
// Sound ComboBox
soundComboBox = new ComboBox
{
DropDownStyle = ComboBoxStyle.DropDownList,
Location = new Point(10, 170),
Size = new Size(150, 25)
};
soundComboBox.Items.AddRange(soundNames);
soundComboBox.SelectedIndex = 3; // Double bip par défaut
this.Controls.Add(soundComboBox);
// Test Sound Button
testSoundButton = new Button
{
Text = "Tester",
Location = new Point(165, 170),
Size = new Size(50, 23),
FlatStyle = FlatStyle.Flat
};
testSoundButton.Click += TestSoundButton_Click;
this.Controls.Add(testSoundButton);
// Volume TrackBar
Label volumeLabel = new Label { Text = "Vol:", Location = new Point(220, 173), Size = new Size(30, 20) };
volumeTrackBar = new TrackBar
{
Minimum = 0,
Maximum = 100,
Value = 70,
TickFrequency = 10,
Location = new Point(250, 170),
Size = new Size(120, 25)
};
volumeTrackBar.ValueChanged += VolumeTrackBar_ValueChanged;
volumeValueLabel = new Label
{
Text = "70%",
Location = new Point(375, 173),
Size = new Size(40, 20)
};
this.Controls.Add(volumeLabel);
this.Controls.Add(volumeTrackBar);
this.Controls.Add(volumeValueLabel);
// Always on top checkbox
alwaysOnTopCheckBox = new CheckBox
{
Text = "Toujours au premier plan",
Location = new Point(10, 205),
Size = new Size(200, 20),
Checked = false
};
alwaysOnTopCheckBox.CheckedChanged += AlwaysOnTopCheckBox_CheckedChanged;
this.Controls.Add(alwaysOnTopCheckBox);
// Reset button
Button resetButton = new Button
{
Text = "Réinitialiser",
Location = new Point(220, 130),
Size = new Size(190, 30),
BackColor = Color.LightCoral,
FlatStyle = FlatStyle.Flat
};
resetButton.Click += (s, e) => StopAndResetTimer();
this.Controls.Add(resetButton);
// Timer
countdownTimer = new System.Windows.Forms.Timer { Interval = 1000 };
countdownTimer.Tick += CountdownTimer_Tick;
// Tray Icon
this.Resize += CookTimerForm_Resize;
// Keyboard shortcuts
this.KeyPreview = true;
this.KeyDown += CookTimerForm_KeyDown;
}
private void VolumeTrackBar_ValueChanged(object sender, EventArgs e)
{
volumeValueLabel.Text = $"{volumeTrackBar.Value}%";
}
private void AlwaysOnTopCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.TopMost = alwaysOnTopCheckBox.Checked;
}
private void TestSoundButton_Click(object sender, EventArgs e)
{
alarmPlayer.Stop();
PlaySound(0.5); // Jouer pendant 0.5 secondes pour le test
}
private void CookTimerForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
StartStopButton_Click(sender, e);
}
else if (e.KeyCode == Keys.Escape)
{
StopAndResetTimer();
}
}
private byte[] GenerateSound(int soundIndex, double durationSeconds, int sampleRate = 44100)
{
int samples = (int)(sampleRate * durationSeconds);
byte[] buffer = new byte[samples * 2]; // 16-bit audio
double amplitude = 0.25 * short.MaxValue * (volumeTrackBar.Value / 100.0); // Volume control
for (int i = 0; i < samples; i++)
{
double t = (double)i / sampleRate;
short sample = 0;
switch (soundIndex)
{
case 0: // Bip classique 440Hz
sample = (short)(amplitude * Math.Sin(2 * Math.PI * 440 * t));
break;
case 1: // Bip aigu 880Hz
sample = (short)(amplitude * Math.Sin(2 * Math.PI * 880 * t));
break;
case 2: // Bip grave 220Hz
sample = (short)(amplitude * Math.Sin(2 * Math.PI * 220 * t));
break;
case 3: // Double bip alternant entre 440Hz et 880Hz
double freq = (i / (sampleRate / 4)) % 2 == 0 ? 440 : 880;
sample = (short)(amplitude * Math.Sin(2 * Math.PI * freq * t));
break;
case 4: // Alarme montante (sweep de 200Hz à 800Hz)
double sweepFreq = 200 + (600 * (t % 3) / 3); // Répète le sweep toutes les 3 secondes
sample = (short)(amplitude * Math.Sin(2 * Math.PI * sweepFreq * t));
break;
case 5: // Alarme sirène (oscillation entre 600Hz et 800Hz)
double modulation = Math.Sin(2 * Math.PI * 4 * t); // 4Hz modulation
double sireneFreq = 700 + 100 * modulation;
sample = (short)(amplitude * Math.Sin(2 * Math.PI * sireneFreq * t));
break;
}
// Fade in/out pour éviter les clics
if (i < sampleRate / 100) // Fade in sur 10ms
{
sample = (short)(sample * i / (sampleRate / 100));
}
else if (i > samples - sampleRate / 100) // Fade out sur 10ms
{
sample = (short)(sample * (samples - i) / (sampleRate / 100));
}
// Convertir en bytes (little-endian)
buffer[i * 2] = (byte)(sample & 0xFF);
buffer[i * 2 + 1] = (byte)(sample >> 8);
}
// Créer le fichier WAV complet
using (MemoryStream ms = new MemoryStream())
{
BinaryWriter writer = new BinaryWriter(ms);
// RIFF header
writer.Write("RIFF".ToCharArray());
writer.Write(36 + buffer.Length);
writer.Write("WAVE".ToCharArray());
// fmt chunk
writer.Write("fmt ".ToCharArray());
writer.Write(16); // Chunk size
writer.Write((short)1); // PCM
writer.Write((short)1); // Mono
writer.Write(sampleRate);
writer.Write(sampleRate * 2); // Byte rate
writer.Write((short)2); // Block align
writer.Write((short)16); // Bits per sample
// data chunk
writer.Write("data".ToCharArray());
writer.Write(buffer.Length);
writer.Write(buffer);
return ms.ToArray();
}
}
private void QuickButton_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if (btn != null)
{
SetTimeAndStart((int)btn.Tag);
}
}
private void SetButton_Click(object sender, EventArgs e)
{
int totalSeconds = (int)hoursInput.Value * 3600 + (int)minutesInput.Value * 60 + (int)secondsInput.Value;
SetTimeAndStart(totalSeconds);
}
private void SetTimeAndStart(int totalSeconds)
{
if (totalSeconds <= 0)
{
MessageBox.Show("Veuillez entrer un temps positif.", "Temps invalide", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
StopAndResetTimer();
remainingSeconds = totalSeconds;
UpdateTimeDisplay();
StartTimer();
}
private void StartStopButton_Click(object sender, EventArgs e)
{
if (isTimerRunning)
{
StopTimer();
}
else
{
if (remainingSeconds == 0)
{
int totalSeconds = (int)hoursInput.Value * 3600 + (int)minutesInput.Value * 60 + (int)secondsInput.Value;
if (totalSeconds <= 0)
{
MessageBox.Show("Veuillez définir un temps avant de démarrer.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
remainingSeconds = totalSeconds;
UpdateTimeDisplay();
}
StartTimer();
}
}
private void StartTimer()
{
if (remainingSeconds > 0 && !isTimerRunning)
{
isTimerRunning = true;
countdownTimer.Start();
startStopButton.Text = "Arrêter";
startStopButton.BackColor = Color.LightCoral;
}
}
private void StopTimer()
{
isTimerRunning = false;
countdownTimer.Stop();
startStopButton.Text = "Démarrer";
startStopButton.BackColor = Color.LightGreen;
alarmPlayer.Stop();
}
private void StopAndResetTimer()
{
StopTimer();
remainingSeconds = 0;
UpdateTimeDisplay();
timeLabel.ForeColor = Color.DarkBlue;
}
private void CountdownTimer_Tick(object sender, EventArgs e)
{
if (remainingSeconds > 0)
{
remainingSeconds--;
UpdateTimeDisplay();
// Changer la couleur quand il reste peu de temps
if (remainingSeconds <= 10)
{
timeLabel.ForeColor = Color.Red;
}
else if (remainingSeconds <= 30)
{
timeLabel.ForeColor = Color.Orange;
}
}
else
{
StopTimer();
UpdateTimeDisplay();
PlayAlarm();
// Flash de la fenêtre
this.WindowState = FormWindowState.Normal;
this.Activate();
this.BringToFront();
MessageBox.Show("Temps écoulé !", "Cook Timer", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void UpdateTimeDisplay()
{
TimeSpan ts = TimeSpan.FromSeconds(remainingSeconds);
timeLabel.Text = string.Format("{0:D2}:{1:D2}:{2:D2}", ts.Hours, ts.Minutes, ts.Seconds);
}
private void PlayAlarm()
{
try
{
int selectedSound = soundComboBox.SelectedIndex;
if (selectedSound >= 0 && selectedSound < soundNames.Length)
{
// Générer un son de 10 secondes qui se répète en boucle
byte[] soundBytes = GenerateSound(selectedSound, 10.0);
using (MemoryStream ms = new MemoryStream(soundBytes))
{
alarmPlayer.Stream = ms;
alarmPlayer.PlayLooping();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Erreur lecture son: " + ex.Message);
}
}
private void PlaySound(double duration)
{
try
{
int selectedSound = soundComboBox.SelectedIndex;
if (selectedSound >= 0 && selectedSound < soundNames.Length)
{
byte[] soundBytes = GenerateSound(selectedSound, duration);
using (MemoryStream ms = new MemoryStream(soundBytes))
{
alarmPlayer.Stream = ms;
alarmPlayer.Play();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Erreur lecture son: " + ex.Message);
}
}
// --- Tray Icon Logic ---
private NotifyIcon trayIcon;
private ContextMenuStrip trayMenu;
private void SetupTrayIcon()
{
trayMenu = new ContextMenuStrip();
trayMenu.Items.Add("Restaurer", null, OnRestoreFromTray);
trayMenu.Items.Add("Quitter", null, OnQuitFromTray);
trayIcon = new NotifyIcon()
{
Icon = SystemIcons.Application,
ContextMenuStrip = trayMenu,
Visible = false,
Text = "Cook Timer"
};
trayIcon.DoubleClick += OnRestoreFromTray;
try
{
this.Icon = new Icon("app_icon.ico");
trayIcon.Icon = new Icon("app_icon.ico");
}
catch { /* Gérer si l'icône n'est pas trouvée */ }
}
private void CookTimerForm_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
if (trayIcon == null) SetupTrayIcon();
trayIcon.Visible = true;
this.ShowInTaskbar = false;
}
}
private void OnRestoreFromTray(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
this.ShowInTaskbar = true;
if (trayIcon != null) trayIcon.Visible = false;
this.Activate();
}
private void OnQuitFromTray(object sender, EventArgs e)
{
Application.Exit();
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (trayIcon != null)
{
trayIcon.Visible = false;
trayIcon.Dispose();
}
base.OnFormClosing(e);
}
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new CookTimerForm());
}
}