I have a little problem. I have a form, which is my login form. Then I also have another form, which is my add user form. When I click on the login button for the login form, it needs to check if the shift and control keys are both held down on the same time. Ff both of them are not pressed, then the add user form should not open. but if they are both pressed down and the login button is clicked, it should show the form.
What I have:
if (Control.ModifierKeys == (Keys.Control & Keys.Shift))
{
//Show the form
}
But this is not working.
When I have:
if (Control.ModifierKeys == Keys.Shift)
{
//Show the form
}
Then it works.
How can I achieve this with both buttons pressed down, control and shift?
Try
Keys.Control | Keys.Shift.This is a flags enumeration; each value is represented by a separate bit in the underlying
int.Keys.Control & Keys.Shiftresults in a zero value – e.g. ifControlis0001andShiftis0010, the bitwise-&is0000.Control.ModifierKeyswill be0000if and only if the user is holding no modifier keys down, so the==will only result intrueif the user isn’t holding anything down.Keys.Control | Keys.Shift, on the other hand, results in a value that says “both these flags” – e.g. ifControlis0001andShiftis0010, the bitwise-|is0011.Control.ModifierKeyswill be0011if and only if the user is holding both Ctrl and Shift down, so the==will only result intruein this case.Alternatively, you could break this down as
The
(value & x) == xconstruct checks whether an individual flagxis set, and after that it’s jsut standard boolean logic.