Windows check if key is pressed

How to check for modifier key presses (Windows Forms .NET)

As the user types keys into your application, you can monitor for pressed modifier keys such as the SHIFT , ALT , and CTRL . When a modifier key is pressed in combination with other keys or even a mouse click, your application can respond appropriately. For example, pressing the S key may cause an «s» to appear on the screen. If the keys CTRL+S are pressed, instead, the current document may be saved.

The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.

If you handle the KeyDown event, the KeyEventArgs.Modifiers property received by the event handler specifies which modifier keys are pressed. Also, the KeyEventArgs.KeyData property specifies the character that was pressed along with any modifier keys combined with a bitwise OR.

If you’re handling the KeyPress event or a mouse event, the event handler doesn’t receive this information. Use the ModifierKeys property of the Control class to detect a key modifier. In either case, you must perform a bitwise AND of the appropriate Keys value and the value you’re testing. The Keys enumeration offers variations of each modifier key, so it’s important that you do the bitwise AND check with the correct value.

For example, the SHIFT key is represented by the following key values:

The correct value to test SHIFT as a modifier key is Keys.Shift. Similarly, to test for CTRL and ALT as modifiers you should use the Keys.Control and Keys.Alt values, respectively.

Detect modifier key

Detect if a modifier key is pressed by comparing the ModifierKeys property and the Keys enumeration value with a bitwise AND operator.

The following code example shows how to determine whether the SHIFT key is pressed within the KeyPress and KeyDown event handlers.

How do I check if a Key is pressed on C++ [closed]

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 4 years ago .

How could I possibly check if a Key is pressed on Windows?

4 Answers 4

As mentioned by others there’s no cross platform way to do this, but on Windows you can do it like this:

The Code below checks if the key ‘A’ is down.

The low-order bit indicates if key is toggled.

Oh and also don’t forget to

There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.

Solution for linux and other posix compliant systems:

Here, for Morgan Mattews’s code provide kbhit() functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.

Solution for windows:

For windows, Microsoft offers _kbhit()

check if a key is pressed, if yes, then do stuff

Consider ‘select()’, if this (reportedly Posix) function is available on your os.

‘select()’ uses 3 sets of bits, which you create using functions provided (see man select, FD_SET, etc). You probably only need create the input bits (for now)

‘select()’ «allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become «ready» for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform a corresponding I/O operation (e.g., read(2) without blocking. )»

When select is invoked:

a) the function looks at each fd identified in the sets, and if that fd state indicates you can do something (perhaps read, perhaps write), select will return and let you go do that . ‘all you got to do’ is scan the bits, find the set bit, and take action on the fd associated with that bit.

Читайте также:  Руководство администратора безопасности linux

The 1st set (passed into select) contains active input fd’s (typically devices). Probably 1 bit in this set is all you will need. And with only 1 fd (i.e. an input from keyboard), 1 bit, this is all quite simple. With this return from select, you can ‘do-stuff’ (perhaps, after you have fetched the char).

b) the function also has a timeout, with which you identify how much time to await a change of the fd state. If the fd state does not change, the timeout will cause ‘select()’ to return with a 0. (i.e. no keyboard input) Your code can do something at this time, too, perhaps an output.

fyi — fd’s are typically 0,1,2. Remembe that C uses 0 as STDIN, 1 and STDOUT.

Simple test set up: I open a terminal (separate from my console), and type the tty command in that terminal to find its id. The response is typically something like «/dev/pts/0», or 3, or 17.

Then I get an fd to use in ‘select()’ by using open:

It is useful to cout this value.

Here is a snippet to consider (from man select):

How to detect the currently pressed key?

In Windows Forms, you can know, at any time, the current position of the cursor thanks to the Cursors class.

The same thing doesn’t seem to be available for the keyboard. Is it possible to know if, for example, the Shift key is pressed?

Is it absolutely necessary to track down every keyboard notification (KeyDown and KeyUp events)?

12 Answers 12

This will also be true if Ctrl + Shift is down. If you want to check whether Shift alone is pressed,

If you’re in a class that inherits Control (such as a form), you can remove the Control.

The code below is how to detect almost all currently pressed keys, not just the Shift key.

You can also look at the following if you use WPF or reference System.Windows.Input

The Keyboard namespace can also be used to check the pressed state of other keys with Keyboard.IsKeyDown(Key), or if you are subscribing to a KeyDownEvent or similar event, the event arguments carry a list of currently pressed keys.

Most of these answers are either far too complicated or don’t seem to work for me (e.g. System.Windows.Input doesn’t seem to exist). Then I found some sample code which works fine: http://www.switchonthecode.com/tutorials/winforms-accessing-mouse-and-keyboard-state

In case the page disappears in the future I am posting the relevant source code below:

Since .NET Framework version 3.0, it is possible to use the Keyboard.IsKeyDown method from the new System.Windows.Input namespace. For instance:

Even though it’s part of WPF, that method works fine for WinForm applications (provided that you add references to PresentationCore.dll and WindowsBase.dll). Unfortunately, however, the 3.0 and 3.5 versions of the Keyboard.IsKeyDown method did not work for WinForm applications. Therefore, if you do want to use it in a WinForm application, you’ll need to be targeting .NET Framework 4.0 or later in order for it to work.

You can P/Invoke down to the Win32 GetAsyncKeyState to test any key on the keyboard.

You can pass in values from the Keys enum (e.g. Keys.Shift) to this function, so it only requires a couple of lines of code to add it.

The best way I have found to manage keyboard input on a Windows Forms form is to process it after the keystroke and before the focused control receives the event. Microsoft maintains a built-in Form -level property named .KeyPreview to facilitate this precise thing:

Then the form’s _KeyDown, _KeyPress, and / or _KeyUp events can be marshaled to access input events before the focused form control ever sees them, and you can apply handler logic to capture the event there or allow it to pass through to the focused form control.

Читайте также:  Как создать образ уже установленной системы windows

Although not as structurally graceful as XAML’s event-routing architecture, it makes management of form-level functions in Winforms far simpler. See the MSDN notes on KeyPreview for caveats.

does work for a text box if the above code is in the form’s keydown event and no other control captures the keydown event for the key down.

Also one may wish stop further key processing with:

The cursor x/y position is a property, and a keypress (like a mouse click/mousemove) is an event. Best practice is usually to let the interface be event driven. About the only time you would need the above is if you’re trying to do a shift + mouseclick thing.

If you need to listen to keys in any generic class what are pressed when a ‘Form’ Window, this is your code. It doesnt listen to global windows key events, so it cannot be used to see keys when the window is not active.

WINDOWS KEY NOT WORKING — Already tried all thing on this forum

My windows key simply stoped working

Now when I try to use WIN+ «something» it selects the icon with the letter I press. Like I press WIN+D(to desktop) it selects the icon with a letter D

Already tried everything I seen in this forum about it nothing seem to work

Replies (55) 

* Please try a lower page number.

* Please enter only numbers.

* Please try a lower page number.

* Please enter only numbers.

Method 1: Disable gaming mode on your keyboard
Some keyboards, usually marketed as “gaming”, have ability to turn off Windows keys via some hardware switch or Fn key combination in order to prevent pressing this key which usually exits your game. The gaming mode key is usually marked with a joystick drawing. Here is how to disable gaming mode on some of the popular gaming keyboards.

On Logitech keyboards, there is a switch above the F1, F2 & F3 function keys that you can flip to the right for gaming mode and to the left for regular use. Flip it to the left. Other versions have a gaming mode button above F4, press the button to toggle in between gaming and standard modes.
In some keyboards, beside the right Ctrl button, instead of a second Windows button, there is a “Win Lock” button (not the menu button). Press it to enable the Windows key.
Corsair keyboards have their own software to adjust lighting, functionality, etc. Run the Corsair software (which has an option to enable/disable the windows key) and enable your Windows key.
The Azio keyboard also has such a switch in the MGK1 series. MGK1 & MGK1-K: Press FN and F9 at the same time. For MGK1-RGB: Press FN and Windows Start Key at the same time.
For the MSI computer/laptop keyboards, you can switch turn on the Windows key from the Dragon Gaming Center > System Tuner.
For the ibuypower keyboard, press fn + ibuypower (aka windows key) to toggle Windows key on and off
For Alienware gaming keyboard, press Fn + F6 to toggle gaming mode on and off
For MS Sidewinder keyboard, go into MS Keyboard & Mouse Center and you can click the Windows key in the dashboard and set it to enabled/disabled
Method 2: Enable Windows Key using registry edit
The registry can allow or restrict a lot including keyboard keys and menu items. To enable your Windows key:

Click Start, type ‘Run’ and click Run, or in Windows 8/10 right click on the start button and click run
Type ‘regedt32’, and then click OK. Click Yes if you get any EULA message asking for confirmation.
On the Windows menu, click HKEY_LOCAL_ MACHINE on Local Machine.
Double-click the System\CurrentControlSet\Control folder, and then click the Keyboard Layout folder.
Right-click the Scancode Map registry entry, and then click Delete.
Click Yes on the confirmation/warning message.
Close Registry Editor and restart the computer.
If you need to disable Windows key again, go to the Microsoft page here and follow the instructions for disabling windows key. You can also use the easy fix tool from here to enable and disable the Windows Key.

Читайте также:  Windows 10 2004 цвет панели задач

Method 3: Re-Register all apps
This will clear any software conflict with your keyboard

Click on the Windows button.
Type ‘PowerShell’ and then right click on ‘Windows PowerShell’ and run as an administrator.
If your start button doesn’t work when you click on it, go to this location: C:\Users\YourUserName\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell\ and right click on “Windows PowerShell” and run as administrator
Type or copy and paste the script below into the PowerShell window and press enter
Get-AppXPackage -AllUsers | Foreach
Restart your PC
Method 4: Enable the start menu
In cases where your start key does not bring up the start menu, there is a possibility the start menu was disabled. To enable it, follow the steps below.

Right click on the Start Button and select “Run” or press Ctrl + Shift + Esc and go to File > click run a new task from task manager.
Type “regedit” (without the quotes)
Navigate to this key
HKEY_CURRENT_USER > Software > Microsoft > Windows > CurrentVersion > Explorer > Advance
Right click on the right hand side panel and create a new DWORD (32-bit) value
Call the new key “EnableXamlStartMenu”
Restart your PC or restart Explorer using task manager as explained in method 5 below.
Method 5: Restart Windows/File Explorer
Explorer controls your Windows user interface. This method will restart Windows/File Explorer and clear any errors that prevented it from starting correctly.

Press Ctrl + Alt + Del on the keyboard and click on task manager.
Click on the Process tab and locate Explorer in the windows and right click on it and select end task.
Click on File and then click on Run New Task.
Type ‘explorer.exe’ and press enter.
Method 6: Turn off filter keys
This has been seen as one of the culprits in Windows 8 and Windows 10 issues. Turning on filterkeys ignores or slows down repeated key strokes and adjusts repeat rates. Somehow, the windows key is also affected on some keyboards. To turn off filter keys:

Drag your mouse to the right edge of your Windows 8 PC and click settings. In windows 10, right click on your start menu and select settings.
From the Windows settings page, scroll down and click on Ease of Access
Click on the keyboard tab on the left hand pane
Scroll down to ‘filter keys’ and turn it off
Method 7: Uninstall and reinstall your keyboard drivers
Uninstalling the bad keyboard drivers will reinstall the correct drivers for your keyboard.

Right click on the Start Button and select “Run” or press Ctrl + Shift + Esc to open task manager and go to File > run a new task.
Type devmgmt.msc and hit enter to open device manager

Expand the ‘Keyboards’ section

Right click on your keyboard drivers and select ‘Uninstall device’
On the warning message that appears, click on ‘Yes’ or ‘Uninstall’ to remove these drivers
If you have a USB keyboard, unplug it then plug it back in. Or restart your computer. Windows will reinstall the drivers automatically. Check if Windows key now functions.
Method 8: Unplug your game controller
Your Windows key might not function some times when your game pad is plugged in and a button is pressed down on the gaming pad. This could be caused by conflicting drivers. It is rear however, but all you need to do is unplug your gamepad or make sure no button is pressed down on your gaming pad or keyboard. Updating your gamepad or keyboard drivers might permanently solve this problem.

Please let me know if one of these will help you solve your concern.

Оцените статью