Detect Shift key is pressed without using events in Windows Forms?

后端 未结 4 563
粉色の甜心
粉色の甜心 2021-01-01 20:05

I need to be able to detect that the shift key is being held, but I don\'t want to use events or global variables to determine that. Is there an API in C# that lets you ask

4条回答
  •  清歌不尽
    2021-01-01 20:17

    if ((Control.ModifierKeys & Keys.Shift) != 0) 
    

    This will also be true if another modifier key is also down (eg, Ctrl+Shift). If you want to check whether Shift alone is pressed without any other modifiers, use

    if (Control.ModifierKeys == Keys.Shift)
    

    Note that even this will be true if another non-modifier is down (Eg, Shift+A). If you want to check whether Shift and only Shift is pressed, you'll have to use an API call.


    If you're in a class that inherits Control (such as a form), you can remove the Control qualifier. (static properties don't need qualifiers in inherited classes)

提交回复
热议问题