How to detect the currently pressed key?

NorthWind picture NorthWind · Jul 8, 2009 · Viewed 248.9k times · Source

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)?

Answer

SLaks picture SLaks · Jul 8, 2009
if ((Control.ModifierKeys & Keys.Shift) != 0) 

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

if (Control.ModifierKeys == Keys.Shift)

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