所以我的 Form 构造函数中有一个无限循环,它将从 Twitch.tv API 加载一个 json 字符串。但是,此应用程序将从任务栏运行。所以我设置了全局热键,当用户按下 F1 时,应该显示一个消息框。我面临的问题是尝试在循环中检测按键。我需要循环播放的原因是我需要知道 twitch 流媒体何时上线或下线。我尝试做一个 Windows 服务,所以我不必做无限循环,但我无法检测到服务中的按键。我知道最好的做法是摆脱循环,但我不确定如何。这是代码。
private KeyHandler ghk;
private System.Timers.Timer liveTime = new System.Timers.Timer();
UserInfo info;
public Form1()
{
InitializeComponent();
ghk = new KeyHandler(Keys.F1, this);
ghk.Register();
while (true)
{
using (var webClient = new System.Net.WebClient())
{
var json = webClient.DownloadString("https://api.twitch.tv/kraken/streams/lirik");
// Now parse with JSON.Net
info = new UserInfo(json);
}
info.streamLive();
if (info.streamLive() && !liveTime.Enabled)
{
liveTime.Start();
}
if (!info.streamLive())
{
liveTime.Stop();
}
}
}
private void HandleHotkey()
{
MessageBox.Show("hello");
}
protected override void WndProc(ref Message m)
{
if (m.Msg == Constants.WM_HOTKEY_MSG_ID)
HandleHotkey();
base.WndProc(ref m);
}
}