tags:

views:

390

answers:

2

I wanted to capture whether a modifier key was being pressed during application startup (to determine fullscreen or windowed).

In the main window constructor I tried checking the Keyboard.Modifiers enum to see if Shift is down. It always showed 'None'.

So I tried a different approach by starting off a DispatcherTimer and checking for shift in its Tick event. Thats seems to work fine.

Question is, is this the best (only) way to do this? And why does the modifier not return the correct value in the window constructor?

A: 

Keyboard.Modifiers is the right class/property to use.

I would suggest checking the modifiers in a handler for the FrameworkElement.Loaded event.

In the Window constructor after InitializeComponent():

this.Loaded += new RoutedEventHandler(Window_Loaded);

And:

void Window_Loaded(object sender, RoutedEventArgs e)
{
    // Examine Keyboard.Modifiers and set fullscreen/windowed
    if ((Keyboard.Modifiers & ModifierKeys.Shift) > 0)
    {
        //SetFullscreen();
    }
}
Josh G
Yep - better than the timer method. But any idea why the modifier doesn't work in the contructor?
PaulB
Not sure. The Keyboard class/device must not initialized yet since the app is just starting up.
Josh G
I'm guessing that you could use Keyboard.Modifiers in the constructor of controls created later, just not the main Window since the app is just starting up.
Josh G
A: 

I bet Keyboard.Modifiers is using GetKeyState under the covers, which probably doesn't work until your message loop has dispatched its first message. GetAsyncKeyState would work for you (via P/Invoke I guess, unless there's a .net way of calling it that I don't know about).

RichieHindle