What I'm trying to achieve is to handle some complex key press and release sequence with Rx. I have some little experience with Rx, but it's clearly not enough for my current undertaking, so I'm here for some help.
My WinForms app is running in the background, only visible in a system tray. By a given key sequence I want to activate one of it's forms. Btw, to hook up to the global key presses I'm using a nice library http://globalmousekeyhook.codeplex.com/ I'm able to receive every key down and key up events, and while key is down multiple KeyDown events are produced (with a standard keyboard repeat rate).
One of example key sequence I want to capture is a quick double Ctrl + Insert key presses (like holding Ctrl key and pressing Insert twice in a given period of time). Here is what I have currently in my code:
var keyDownSeq = Observable.FromEventPattern<KeyEventArgs>(m_KeyboardHookManager, "KeyDown");
var keyUpSeq = Observable.FromEventPattern<KeyEventArgs>(m_KeyboardHookManager, "KeyUp");
var ctrlDown = keyDownSeq.Where(ev => ev.EventArgs.KeyCode == Keys.LControlKey).Select(_ => true);
var ctrlUp = keyUpSeq.Where(ev => ev.EventArgs.KeyCode == Keys.LControlKey).Select(_ => false);
But then I'm stuck. My idea is that I need somehow to keep track of if the Ctrl key is down. One way is to create some global variable for that, and update it in some Merge listener
Observable.Merge(ctrlDown, ctrlUp)
.Do(b => globabl_bool = b)
.Subscribe();
But I think it ruins the whole Rx approach. Any ideas on how to achieve that while staying in Rx paradigm?
Then while the Ctrl is down I need to capture two Insert presses within a given time. I was thinking about using the Buffer:
var insertUp = keyUpSeq.Where(ev => ev.EventArgs.KeyCode == Keys.Insert);
insertUp.Buffer(TimeSpan.FromSeconds(1), 2)
.Do((buffer) => { if (buffer.Count == 2) Debug.WriteLine("happened"); })
.Subscribe();
However I'm not sure if it's most efficient way, because Buffer will produce events every one second, even if there was no any key pressed. Is there a better way? And I also need to combine that with Ctrl down somehow.
So once again, I need to keep track of double Insert press while Ctrl is down. Am I going in the right direction?
P.S. another possible approach is to subscribe to Insert observable only while Ctrl is down. Not sure how to achieve that though. Maybe some ideas on this as well?
EDIT: Another problem I've found is that Buffer doesn't suit my needs exactly. The problem comes from the fact that Buffer produces samples every two seconds, and if my first press belongs to the first buffer, and second to the next one, then nothing happens. How to overcome that?