How can get the correct Handler of an object? - vb.net

I am making an application that requires generating panels dynamically, and in turn that each panel generated two events, one with left click and another with right mouse click.
The right click is the one that gives me trouble since I have not been able to call a Handler that I have put temporarily in the event of the left click, but now that I see that it works, I want to pass it to the ToolStripMenuItem event, but when it enters event, the sender takes ownership of the ToolStripMenuItem and in this case you would need the property "System.Windows.Forms.Panel" in order to work on the Panel object.
I am not sure if I am doing it correctly, can you support me with any idea how to do it?
Annex the code of what I have developed so far
Public Class Form1
Dim pb, pbdoors As New Panel
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim pos As Int32 = 20
Dim contador As Int16 = 1
For i As Int16 = 1 To 3
Dim pb As New Panel With
{
.Width = 120,
.Height = 460,
.Top = 10,
.Left = 10,
.Name = "Panel" & contador,
.Location = New Point(pos, 20)
}
AddHandler pb.Click, AddressOf myClickHandler_b
Me.Panel1.Controls.Add(pb)
pb.BringToFront()
pos = pos + 120
contador = contador + 1
Next
End Sub
End Class
Public Sub myClickHandler_b(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim pos As Integer = Val(TextBox38.Text)
Dim clickedLabel As Panel = DirectCast(sender, Panel)
clickedLabel.Location = New Point((clickedLabel.Location.X + 120), clickedLabel.Location.Y)
TextBox38.Text = pos
End Sub
Private Sub ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem1.Click
myClickHandler_b(sender, e)
End Sub

In order to recognize which mouse button is clicked you should use MouseClick as event handler.
The piece of code starting with and working on that is: “AddHandler pb.MouseClick……….”
I hope this might help you:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim pos As Int32 = 20
Dim contador As Int16 = 1
For i As Int16 = 1 To 3
Dim pb As New Panel With
{
.Width = 120,
.Height = 460,
.Top = 10,
.Left = 10,
.Name = "Panel" & contador,
.Location = New Point(pos, 20)
}
AddHandler pb.MouseClick, Sub(senderO As Object, eObj As MouseEventArgs)
If eObj.Button = MouseButtons.Left Then
'Do your tasks here
MsgBox("Left button clicked")
ElseIf eObj.Button = MouseButtons.Right Then
'Do your tasks here
MsgBox("Right button clicked")
End If
End Sub
Me.Panel1.Controls.Add(pb)
pb.BringToFront()
pos = pos + 120
contador = contador + 1
Next
End Sub

Winforms only provides a single event (Click) for both mouse buttons. You need to check (and cast, given that signature) the event arguments to know when you have a right click:
Public Sub myClickHandler_b(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim mouseevent As MouseEventArgs = TryCast(e, MouseEventArgs)
If mouseevent IsNot Nothing AndAlso mouseevent.Button = MouseButtons.Right Then
RightClick(TryCast(sender, Panel))
Exit Sub
End If
'Left Click
'Ugh. Val() is not your friend.
Dim pos As Integer = Val(TextBox38.Text)
Dim clickedLabel As Control = DirectCast(sender, Control)
clickedLabel.Location = New Point((clickedLabel.Location.X + 120), clickedLabel.Location.Y)
TextBox38.Text = pos
End Sub
Public Sub RightClick(source As Panel)
End Sub
Now for the second part. In the ToolStripMenuItem1_Click() method, if you have several dynamic panels on your form, how is the method supposed to know which panel it's working with? You need something in this code knows that information, and uses it for the sender argument. Additionally, given the new handling for left vs right clicks, you also need to think carefully about how that will spill over into the click handler.
So ToolStripMenuItem1_Click() should look something (but probably not exactly!) like this:
Private Sub ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem1.Click
myClickHandler_b(pb, Nothing)
End Sub

Related

VB fires changetext event before control is loaded

I need to add some controls to a Visual Basic 2017 form programmatically. One of the controls is a textbox that needs a changetext event handler. Below is some code that accomplishes that task.
HOWEVER, the changetext event handler seems to fire right away, before the form even loads... before the textbox itself even loads! A "click" handler works fine, as expected. But changetext? Nope.
I've thrown together a simplified version to demonstrate. The line with the "DIES RIGHT HERE" comment causes the problem (not the comment, but the code to the left of it).
A textbox that is added at design time will work fine, not cause this problem, but that isn't an option.
What's causing this the changetext handler to be run early? How do I work around this?
Public Class Form1
Dim txtTest As TextBox
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim pntTextBox As Point
pntTextBox.X = 100
pntTextBox.Y = 100
txtTest = New TextBox
With txtTest
.Location = pntTextBox
.Width = 100
AddHandler txtTest.TextChanged, AddressOf txtTest_TextChanged
End With
Me.Controls.Add(txtTest)
End Sub
Private Sub txtTest_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyClass.TextChanged
Dim strTest As String
strTest = Str(txtTest.Width) ' ****** DIES RIGHT HERE
MsgBox(strTest)
End Sub
End Class
Made a few changes. Works.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For x As Integer = 1 To 2 'create multiple TB's
Dim pntTextBox As Point
pntTextBox.X = 100 * x
pntTextBox.Y = 100
Dim txtTest As TextBox = New TextBox
With txtTest
txtTest.Name = "tb_" & x.ToString
AddHandler txtTest.TextChanged, AddressOf txtTest_TextChanged
.Location = pntTextBox
.Width = 100
End With
Me.Controls.Add(txtTest)
Next
End Sub
Private Sub txtTest_TextChanged(ByVal sender As Object,
ByVal e As System.EventArgs) 'no handler at design time
Dim tb As TextBox = DirectCast(sender, TextBox)
Dim strTest As String
strTest = tb.TextLength.ToString
Debug.WriteLine("{0} {1}", tb.Name, strTest) 'put breakpoint here
End Sub
End Class

Smart Phone Like Scrolling Solution issue (vb.net)

This solution seems to be the best one out there and the most commonly accepted one - however, if you scroll to the bottom and touch a the actual flowcontrol behind the buttons (I tried to make this so that there would be empty space to make this sample test easier), you then have to double tap-and-hold the button for the scrolling to resume. Restarting the application restores the phone-like scrolling functionality. I am wondering if anyone else has seen this or figured it out - try it with your apps and see if it is the case as well. I modified the snippet above so that you can start a new project, copy and paste this into form1's code, and hit run.
Public Class Form1
Dim FlowPanel As New FlowLayoutPanel
Private Function GenerateButton(ByVal pName As String) As Button
Dim mResult As New Button
With mResult
.Name = pName
.Text = pName
.Width = 128
.Height = 128
.Margin = New Padding(0)
.Padding = New Padding(0)
.BackColor = Color.CornflowerBlue
AddHandler .MouseDown, AddressOf Button_MouseDown
AddHandler .MouseMove, AddressOf Button_MouseMove
End With
Return mResult
End Function
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Me.Width = 806
Me.Height = 480
FlowPanel.Padding = New Padding(0)
FlowPanel.Margin = New Padding(0)
' FlowPanel.ColumnCount = Me.Width / (128 + 6)
FlowPanel.Dock = DockStyle.Fill
FlowPanel.AutoScroll = True
Me.Controls.Add(FlowPanel)
Dim i As Integer
For i = 1 To 98
FlowPanel.Controls.Add(GenerateButton("btn" & i.ToString))
Next
End Sub
Dim myMouseDownPoint As Point
Dim myCurrAutoSMouseDown As Point
Private Sub Button_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
myMouseDownPoint = PointToClient(Cursor.Position)
myCurrAutoSMouseDown = FlowPanel.AutoScrollPosition
End Sub
Private Sub Button_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs)
If e.Button = Windows.Forms.MouseButtons.Left Then
Dim mLocation As Point = PointToClient(Cursor.Position)
If myMouseDownPoint <> mLocation Then
Dim mCurrAutoS As Point
Dim mDeslocation As Point = myMouseDownPoint - mLocation
mCurrAutoS.X = Math.Abs(myCurrAutoSMouseDown.X) + mDeslocation.X
mCurrAutoS.Y = Math.Abs(myCurrAutoSMouseDown.Y) + mDeslocation.Y
FlowPanel.AutoScrollPosition = mCurrAutoS
End If
End If
End Sub
End Class
Thanks for the code , I made ​​some changes to improve behavior . I hope it can be useful to someone .
Dim myMouseDownPoint As Point
Dim myCurrAutoSMouseDown As Point
'Add boolean variable a true.
Private _ValidateClickEvent As Boolean = True
Private Sub MyMouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
myMouseDownPoint = PointToClient(Cursor.Position)
myCurrAutoSMouseDown = Panel1.AutoScrollPosition
End Sub
' Add MouseUp event for return the boolean variable a true.
Private Sub MyMouseUp(ByVal sender As Object, ByVal e As MouseEventArgs)
_ValidateClickEvent = True
End Sub
'Set boolean variable a false when change mlocation.
Private Sub MyMouseMove(ByVal sender As Object, ByVal e As MouseEventArgs)
If e.Button = Windows.Forms.MouseButtons.Left Then
Dim mLocation As Point = PointToClient(Cursor.Position)
If myMouseDownPoint <> mLocation Then
Dim mCurrAutoS As Point
Dim mDeslocation As Point = CType(myMouseDownPoint - mLocation, Size)
mCurrAutoS.X = Math.Abs(myCurrAutoSMouseDown.X) + mDeslocation.X
mCurrAutoS.Y = Math.Abs(myCurrAutoSMouseDown.Y) + mDeslocation.Y
Panel1.AutoScrollPosition = mCurrAutoS
_ValidateClickEvent = False
End If
End If
End Sub
' Test boolean variable to perform click event.
Private Sub MyClick(sender As System.Object, e As System.EventArgs)
If _ValidateClickEvent Then
........................
Else
_ValidateClickEvent = True
End If
End Sub

Creating Dynamic Controls in VB and having them pre-programmed in different events

I have a project that can create a picturebox control but I want every picturebox the user creates to have events already set in place such as the mouse down and mouse up events. But since the control hasnt been created yet, I can't refer to it in the code without getting an error and the form not being able to load because of it. In other words, after the user creates a picturebox, they can move the picturebox around the screen and draw on it. Then they can create another picturebox and move it around and draw on it as well and arrange the pictureboxes as they please. Any ideas? Thanks.
here is my code:
Private Sub AddCanvasToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddCanvasToolStripMenuItem.Click
Dim canvas As New PictureBox
Dim i As Integer = 0
i = i + 1
canvas.Name = "canvas"
canvas.BackColor = Color.White
canvas.BorderStyle = BorderStyle.FixedSingle
canvas.Image = Nothing
canvas.Height = 200
canvas.Width = 200
AddHandler canvas.MouseDown, AddressOf PictureBox1_MouseDown
AddHandler canvas.MouseMove, AddressOf PictureBox1_MouseMove
canvas.Top = Panel2.Bottom
canvas.Left = Panel1.Right
Controls.Add(canvas)
End Sub
Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
If RadioButton1.Checked = True Then
xpos = Cursor.Position.X - PictureBox1.Location.X
ypos = Cursor.Position.Y - PictureBox1.Location.Y
End If
If RadioButton2.Checked = True Then
down = True
If down = True Then
PictureBox1.CreateGraphics.FillEllipse(mybrush, e.X, e.Y, 2, 2)
End If
End If
End Sub
Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
If RadioButton1.Checked = True Then
If e.Button = Windows.Forms.MouseButtons.Left Then
pos = MousePosition
pos.X = pos.X - xpos
pos.Y = pos.Y - ypos
PictureBox1.Location = pos
End If
End If
If down = True Then
PictureBox1.CreateGraphics.FillEllipse(mybrush, e.X, e.Y, 2, 2)
End If
End Sub
But this only makes what I want to happen to canvas happen to picturebox1.
I dont even want picturebox1 to exist in the first place. I want them to create a new picturebox out of nowhere with events already programmed into it. So the user can create a new picturebox and then move it and draw on it.
Create events dynamically too, Like this:
Private Sub AddCanvasToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddCanvasToolStripMenuItem.Click
Dim canvas As New PictureBox
Dim i As Integer = 0
i = i + 1
canvas.Name = "canvas"
canvas.BackColor = Color.White
canvas.BorderStyle = BorderStyle.FixedSingle
canvas.Image = Nothing
canvas.Height = 200
canvas.Width = 200
AddHandler canvas.MouseDown, AddressOf pic_MouseDown
canvas.Top = Panel2.Bottom
canvas.Left = Panel1.Right
Controls.Add(canvas)
End Sub
Private Sub pic_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)
'Do Something
End Sub
The above is perfect, but just to expand a little bit more:
Private Sub btnAddPictureBox_Click(sender As Object, e As EventArgs) Handles btnAddPictureBox.Click
Dim newPicBox As New PictureBox
Me.Controls.Add(newPicBox)
newPicBox.Location = New Point(50, 50)
newPicBox.Height = 100
newPicBox.Width = 100
newPicBox.BackColor = Color.White
newPicBox.BorderStyle = BorderStyle.FixedSingle
AddHandler newPicBox.MouseClick, AddressOf PictureBoxMouseClick
End Sub
Private Sub PictureBoxMouseClick(sender As Object, e As MouseEventArgs)
'Access the control the raised the event
'In this case we are changing the background colour to red
DirectCast(sender, PictureBox).BackColor = Color.Red
End Sub

How to handle a variable amount of buttons clicked?

I have a pretty basic problem with button clicks in VB.Net I cannot seem to figure out.
First, I am creating a variable amount of buttons and adding them to the parent form.
Private Sub CreateUIObjects()
For i As Integer = 1 To NumberOfButtons
Dim button As Button = New Button()
Me.Controls.Add(button)
Next
End Sub
I know it is possible to handle a fixed amount of buttons clicked with the following code
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click, Button2.Click, Button3.Click '... And so on
Dim b As Button = CType(sender, Button)
End Sub
But what do I do with not 3, but a variable amount of buttons?
Some code to experiment with
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CreateUIObjects(3)
End Sub
Dim myButtonNames As String = "foobar"
Private Sub myButtonsClick(sender As Object, e As EventArgs)
Dim b As Button = DirectCast(sender, Button)
Debug.WriteLine(b.Name)
End Sub
Private Sub CreateUIObjects(NumberOfButtons As Integer)
Static ct As Integer = 0
For i As Integer = 1 To NumberOfButtons
ct += 1
Dim btn As Button = New Button()
btn.Name = myButtonNames & ct.ToString
btn.Text = btn.Name
btn.Location = New Point(ct * 20, ct * 20)
AddHandler btn.Click, AddressOf myButtonsClick
Me.Controls.Add(btn)
Next
End Sub
You can use something like this
AddHandler Button1.Click, AddressOf Button_Click
take a look http://msdn.microsoft.com/en-us/library/ms172877.aspx

How to programmatically add controls to a form in VB.NET

I am working on an inventory in Visual Basic 2010 Express Edition. I don't know the number of fields that will be necessary for the inventory. My hope was that I could add textboxes/checkboxes/buttons using for loops in the program. Is there a way to add controls to a form without using the toolbox?
Can I add controls by instantiating them in the program?
Yes.
Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim MyTextbox as New Textbox
With MyTextbox
.Size = New Size(100,20)
.Location = New Point(20,20)
End With
AddHandler MyTextbox.TextChanged, AddressOf MyTextbox_Changed
Me.Controls.Add(MyTextbox)
'Without a help environment for an intelli sense substitution
'the address name and the methods name
'cannot be wrote in exchange for each other.
'Until an equality operation is prior for an exchange i have to work
'on an as is base substituted.
End Sub
Friend Sub MyTextbox_Changed(sender as Object, e as EventArgs)
'Write code here.
End Sub
Dim numberOfButtons As Integer
Dim buttons() as Button
Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Redim buttons(numberOfbuttons)
for counter as integer = 0 to numberOfbuttons
With buttons(counter)
.Size = (10, 10)
.Visible = False
.Location = (55, 33 + counter*13)
.Text = "Button "+(counter+1).ToString ' or some name from an array you pass from main
'any other property
End With
'
next
End Sub
If you want to check which of the textboxes have information, or which radio button was clicked, you can iterate through a loop in an OK button.
If you want to be able to click individual array items and have them respond to events, add in the Form_load loop the following:
AddHandler buttons(counter).Clicked AddressOf All_Buttons_Clicked
then create
Private Sub All_Buttons_Clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
'some code here, can check to see which checkbox was changed, which button was clicked, by number or text
End Sub
when you call: objectYouCall.numberOfButtons = initial_value_from_main_program
response_yes_or_no_or_other = objectYouCall.ShowDialog()
For radio buttons, textboxes, same story, different ending.
Public Class Form1
Private boxes(5) As TextBox
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim newbox As TextBox
For i As Integer = 1 To 5 'Create a new textbox and set its properties26.27.
newbox = New TextBox
newbox.Size = New Drawing.Size(100, 20)
newbox.Location = New Point(10, 10 + 25 * (i - 1))
newbox.Name = "TextBox" & i
newbox.Text = newbox.Name 'Connect it to a handler, save a reference to the array & add it to the form control.
AddHandler newbox.TextChanged, AddressOf TextBox_TextChanged
boxes(i) = newbox
Me.Controls.Add(newbox)
Next
End Sub
Private Sub TextBox_TextChanged(sender As System.Object, e As System.EventArgs)
'When you modify the contents of any textbox, the name of that textbox
'and its current contents will be displayed in the title bar
Dim box As TextBox = DirectCast(sender, TextBox)
Me.Text = box.Name & ": " & box.Text
End Sub
End Class
To add controls dynamically to the form, do the following code. Here we are creating textbox controls to add dynamically.
Public Class Form1
Private m_TextBoxes() As TextBox = {}
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
' Get the index for the new control.
Dim i As Integer = m_TextBoxes.Length
' Make room.
ReDim Preserve m_TextBoxes(i)
' Create and initialize the control.
m_TextBoxes(i) = New TextBox
With m_TextBoxes(i)
.Name = "TextBox" & i.ToString()
If m_TextBoxes.Length < 2 Then
' Position the first one.
.SetBounds(8, 8, 100, 20)
Else
' Position subsequent controls.
.Left = m_TextBoxes(i - 1).Left
.Top = m_TextBoxes(i - 1).Top + m_TextBoxes(i - _
1).Height + 4
.Size = m_TextBoxes(i - 1).Size
End If
' Save the control's index in the Tag property.
' (Or you can get this from the Name.)
.Tag = i
End With
' Give the control an event handler.
AddHandler m_TextBoxes(i).TextChanged, AddressOf TextBox_TextChanged
' Add the control to the form.
Me.Controls.Add(m_TextBoxes(i))
End Sub
'When you enter text in one of the TextBoxes, the TextBox_TextChanged event
'handler displays the control's name and its current text.
Private Sub TextBox_TextChanged(ByVal sender As _
System.Object, ByVal e As System.EventArgs)
' Display the current text.
Dim txt As TextBox = DirectCast(sender, TextBox)
Debug.WriteLine(txt.Name & ": [" & txt.Text & "]")
End Sub
End Class
You can get your Button1 location and than increase the Y value every time you click on it.
Public Class Form1
Dim BtnCoordinate As Point
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim btn As Button = New Button
BtnCoordinate.Y += Button1.Location.Y + 4
With btn
.Location = New Point(BtnCoordinate)
.Text = TextBox1.Text
.ForeColor = Color.Black
End With
Me.Controls.Add(btn)
Me.StartPosition = FormStartPosition.CenterScreen
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Button1Coordinate = Button1.Location
End Sub
End Class