2

Can someone kindly explain how this works?

if ((Control.MouseButtons & MouseButtons.Left) != 0)

MSDN only says that Control.MouseButtons Property gets a value indicating which of the mouse buttons is in a pressed state but I can't understand how that '&' works and why should it be different than 0.

EricLaw
  • 56,563
  • 7
  • 151
  • 196
Aaron Ullal
  • 4,855
  • 8
  • 35
  • 63

2 Answers2

2

The MouseButtons property is a bit flag vs. a normal enum. That means it can simultaneously hold values like MouseButtons.Left and MouseButtons.Right. It does this by using the 1 / 0 states of specific bits within the value to represent states. MouseButtons.Left and MouseButtons.Right represent such states.

The & operation is known as bitwise and. It will return a value which has the bits which were 1 in both the left and the right value. Hence this particular expression will only be non-zero when the MouseButtons.Left bit is set in MouseButtons meaning that the left button is indeed pressed

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
1

Control.MouseButtons is a bitwise combination.

The expression:

if ((Control.MouseButtons & MouseButtons.Left) != 0)

is checking if the bit MouseButtons.Left is set (has value 1).

Alberto
  • 15,626
  • 9
  • 43
  • 56