tags:

views:

447

answers:

3

When my appliactions starts up in the static void Main Methode I want to determine if a key like Alt or Ctrl is pressed and then start the Application in some kind of Option-Mode. How can I find out if a key is pressed during startup?

I found some samples already but they all import a windows dll. Something I don't want to do.

+2  A: 

Use Keyboard.IsKeyDown() static method will help you to check the state of the keys you're interested in.

if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)
       || Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt) )
{
    //Load in a special mode
}
else
{
    //Load standard mode
}
ArsenMkrt
A: 

If you really need to do it in the main method you will have to use

[DllImport("user32.dll")]
public static extern int GetKeyboardState(byte [] lpKeyState);

docs here

because the Keyboard static members that you'd normally use do not work at that point:

Keyboard.Modifiers Keyboard.IsKeyDown

But you could try to hookup to the Application.Startup event and do your keyboard testing there.

bitbonk
he doesn't wanna do DLL Imports. Probably looking a way that is inside the .net namespaces itself.
vikramjb
You don't need to import anything when using Keyboard.Modifiers. But there is a slight chance that Keyboard.IsKeyDown and Keyboard.Modifiers do not work at the begging of the main method. Thats where he wants to use it. That's why I introduced him to GetKeyboardState. this will work in any case. There is nothing wrong or bad in using Dllimport unless you are in sliverlight of course.
bitbonk
Indeed it seems IsKeyDown in not working inside main. Will try something else.
Holli
As I said, there is nothing wrong with dllimport but you could try to hookup to the Application.Startup event and do your keyboard test there. I add this to my answer.
bitbonk
A: 

You might want to check this question [SO]

I had the same problem and ended up checking for the keyboard modifiers in the Loaded event...

PaulB
Not exactly what I had in mind. I want to check the keys before any window is loaded because if the Ctrl-Key is pressed during startup I want to load a completely different window.GetKeyboardState is the only thing that seems to work inside the main-method.
Holli
Ah ... fair enough :)
PaulB