2014-09-10 81 views
1

因此,我的表单构造函数中有一个无限循环,它将从Twitch.tv API加载json字符串。但是这个应用程序将从任务栏运行。所以我设置了全球热键,当用户点击F1时,应该显示一个消息框。我面临的问题是在循环中尝试检测按键。我需要循环的原因是我需要知道什么时候抽动拖缆已经联机或脱机。我尝试做一个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); 
    } 
} 

回答

2

好了,最简单的解决方法是运行在另一个线程的无限循环,所以它不会阻止你的主线程,这将使其能够收到和处理事件,像这样:

new Thread(delegate() { 

while(true) 
{ 
//... 
} 

}).Start(); 
+0

完美正是我需要的! – Valener 2014-09-10 23:03:20