Freestyle Coding

Programming in the Real World

  Home  |   Contact  |   Syndication    |   Login
  53 Posts | 0 Stories | 39 Comments | 0 Trackbacks

News

Tag Cloud


Archives

Post Categories

Charity

Conferences

Professional

Projects

Social Networks

Last night, I was playing around with my port. I was having a bit of a problem getting the mouse click to behave as I expected. In a fit of inspiration, I solved that problem in such a way that it allowed me to dramatically improve the keyboard buffer. With the popularity of the keyboard buffer, I thought I'd share right away.

As I stated in the original post about the keyboard buffer, WinRT doesn't route keyboard events unless there is a valid target. This forced me to have a control that required focus. This wasn't really a problem, unless the control lost focus.

Of course, we have to place our control on the screen. Furthermore, we have to place it on some sort of monolithic control that handles everything. Thus, why don't we just ask the Canvas to pass us these events?

public class KeyboardBuffer : Control {
private List<VirtualKey> PressedKeys;
 
public KeyboardBuffer() {
PressedKeys = new List<VirtualKey>();
this.Loaded += ControlLoaded;
}
 
private void ControlLoaded( object sender, RoutedEventArgs e ) {
FrameworkElement _Parent = this.Parent as FrameworkElement;
while( !(_Parent is Canvas) )
_Parent = _Parent.Parent as FrameworkElement;
 
_Parent.KeyDown += KeyDownEvent;
_Parent.KeyUp += KeyUpEvent;
}
 
void KeyDownEvent( object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e ) {
if( !PressedKeys.Contains( e.Key ) ) {
PressedKeys.Add( e.Key );
switch( e.Key ) {
// HANDLE KEYS HERE
}
}
}
 
void KeyUpEvent( object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e ) {
while( PressedKeys.Remove( e.Key ) );
 
switch( e.Key ) {
// HANDLE KEYS HERE
}
}
}

Now, I just go up the chain and find the Canvas. At that point, I attach to its events. This way, I always get them. Mouse clicks, screen manipulation, throwing your Surface across the room? Doesn't matter. The events are bound so far up the chain that you always get them. You don't have to focus on the focus.

If you are reading this article without ever reading the original article, there are a few other things I'm leaving out. Check out the original post about the keyboard buffer if it seems like I'm not mentioning something.

posted on Wednesday, February 20, 2013 11:27 AM