-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathClockAppContext.cs
94 lines (86 loc) · 2.83 KB
/
ClockAppContext.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IntervalClock.Forms;
using IntervalClock.Properties;
using NAudio.Vorbis;
using NAudio.Wave;
namespace IntervalClock
{
public class ClockAppContext:ApplicationContext
{
private readonly NotifyIcon _trayIcon;
private readonly ClockTimer _timer;
private readonly SynchronizationContext _syncContext;
public ClockAppContext()
{
_trayIcon = new NotifyIcon()
{
Icon = Resources.MyIcon,
ContextMenuStrip = new ContextMenuStrip()
{
Items =
{
new ToolStripMenuItem("设置",null,OpenSettings),
new ToolStripMenuItem("退出", null, Exit)
}
},
Visible = true,
};
_trayIcon.DoubleClick += OpenSettings;
// 捕获主线程的 SynchronizationContext
_syncContext = SynchronizationContext.Current!;
// 生成Timer和对应的方法
_timer = new ClockTimer(PlaySoundAndShow);
}
private void PlaySoundAndShow()
{
Debug.WriteLine("时间到");
_syncContext.Post(_ =>
{
new ClockForm().Show();
},null);
Task.Run(() =>
{
using var outputDevice = new WaveOutEvent();
if (!ClockConfig.Instance.SoundPath.Equals(""))
{
try
{
using var audioFile = new AudioFileReader(ClockConfig.Instance.SoundPath);
outputDevice.Init(audioFile);
}
catch
{
MessageBox.Show("音频无法正常播放,请更换音频文件");
return;
}
}
else
{
using var audioFile = new MemoryStream(Resources.ClockSound) ;
using var vorbisReader = new VorbisWaveReader(audioFile) ;
outputDevice.Init(vorbisReader);
}
outputDevice.Play();
// 等待音频播放完成
while (outputDevice.PlaybackState == PlaybackState.Playing)
{
Thread.Sleep(100);
}
});
}
private void OpenSettings(object? sender, EventArgs e)
{
new SettingsForm(_timer).Show();
}
private void Exit(object? sender, EventArgs e)
{
_trayIcon.Visible = false;
Application.Exit();
}
}
}