Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing the windows key in c# (wpf)

Tags:

c#

wpf

keyboard

I have written a small program displaying sounds and images on the screen when pushing any button. I always start it when one of my little kids crawls onto my lap and start hitting the keys, of course, randomly.

It works fine except for 2 keys, one of them being the ON/OFF switch, the other being the Windows-key. (the CTRL-ESC equivalent I believe) I can intercept it as it is pressed, but only after the startmenu is showing.

The event I use is the UIElement.KeyDown and all I could came up with so far is : (the e being KeyEventArgs)

            if (e.Key == Key.LWin) e.Handled = true;

but than the start window is already showing I'm afraid.

I have already 1 answer but would very much like to know if there's any wpf-support?

I suspect programming the main on/off switch might not be possible? Otherwise, any help there would be welcome too..

like image 870
Peter Avatar asked Apr 20 '09 09:04

Peter


People also ask

How do I find the Windows key on my keyboard?

It is labeled with a Windows logo, and is usually placed between the Ctrl and Alt keys on the left side of the keyboard; there may be a second identical key on the right side as well. Pressing Win (the Windows key) on its own will do the following: Windows 11: Bring up the Start menu.

How do I press a Windows key without a key?

If your keyboard lacks the Windows logo key, you can use the Ctrl + Esc hotkey to open the Start menu. Yes, in addition to the Windows logo key, the Start menu can also be opened with the Ctrl + Esc on all keyboards.

Is a device independent keycode?

Virtual-key codes are device-independent. Pressing the A key on any keyboard generates the same virtual-key code.


2 Answers

You'll need a keyboard hook. Unfortunately, this has to be done with P/Invoke; it can't be done with managed code.

Check out Baby Smash! by Scott Hanselman. It's hosted on code plex at http://www.codeplex.com/babysmash Github at https://github.com/shanselman/babysmash

Alternatively, check out ShapeShow on CodeProject, which is similar.

like image 76
abhilash Avatar answered Sep 22 '22 09:09

abhilash


See http://msdn.microsoft.com/en-us/library/system.windows.input.key(v=VS.90).aspx

At the bottom you'll see a simple example, I think what you're looking for is something along these lines:

left windows key: System.Windows.Input.Key.LWin

right windows key: System.Windows.Input.Key.RWin

example:

private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
    if (e.Key == Key.LWin) {
        textBlock1.Text = "You Entered: " + textBox1.Text;
    }
}
like image 40
merrick Avatar answered Sep 22 '22 09:09

merrick