Search code examples
c#keypresstwitch

Detect Key Press while looping infinitely


So i have an infinite loop in my Form constructor that will load up a json string from Twitch.tv API. However this application will be ran from the taskbar. So I have set up global hotkey for when the user hits F1 a messagebox should show up. The problem I'm facing is trying to detect a keypress while in the loop. Th reason I need to loop is i need to know when the twitch streamer has gone online or offline. I tried doing a windows service so I don't have to do the infinite loop but I can't detect key presses in a service. I know the best course of action is to get rid of the loop but I'm not sure how. Here is the code.

 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);
    }
}

Solution

  • Well, the most simple workaround is to run the infinite loop in another thread so it will not block your main thread which will make it possible to recieve and handle events, something like this:

    new Thread(delegate() { 
    
    while(true)
    {
     //...
    }
    
    }).Start();