3

Well,I am beginner in Vb.NET although I had started learning few years back then took break again started and again break. So,anyways I am still the beginner and I am unable to understand what this WithEvents actually does and how and when to be used?I was studying on Dim and came across Dim WithEvents. I tried finding articles but all of them got bit higher level programming code compared to my level so it's gonna take time for me to reach that level.Until then for now I want to know WithEvents actual usage. Can someone give me any simple program that can be the clarity of WithEvents?

Source Links : Generic WithEvents

VB.NET: WithEvents not Working

Strange WithEvents thing

WithEvents+Handles+Overrides

in vb.net how do I declare a public variable from a private sub

https://msdn.microsoft.com/en-us/library/stf7ebaz(v=vs.90).aspx

Thank you.

Peter Bons
  • 26,826
  • 4
  • 50
  • 74
thebeginning
  • 31
  • 1
  • 5

1 Answers1

6

In short, WithEvents tells VB that the object you are declaring can raise events and that you intend to handle those events. This keyword goes hand in hand with the Handles keyword.

Create a new form and then add a button to it. Then double-click the button. VB will generate code similar to the following (notice the Handles keyword):

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

End Sub

What you don't immediately see is the declaration for the button. If you look into the Form1.Designer.vb file you will see a line like this:

Friend WithEvents Button1 As System.Windows.Forms.Button

Notice the WithEvents. Since the button will raise events, the variable must be declared using that keyword.

Chris Dunaway
  • 10,974
  • 4
  • 36
  • 48