Using the same event handler for multiple buttons - vb.net

I have 15 buttons created through design.
I want them to have a background picture whenever I click on any of them, for example:
If I click on button11 then its background will be "Hello.jpg"
If click button12 then its background will be become "Hello.jpg"
Is there a method to write a code instead of writing code for individual button?
The code should detect which button I clicked and then change its background.
Private Sub e_11_Click(sender As Object, e As EventArgs) Handles e_11.Click
e_11.Image = Image.FromFile("E:\battleship\Explode.gif")
End Sub
Is there a way that handles every button click?

Yes, you can bind the same method to multiple controls:
Private Sub MyButtons_Click(sender As Object, e As EventArgs) _
Handles e_1.Click, e_2.Click, e_3.Click, ...
Dim myButton = DirectCast(sender, Button)
myButton.Image = Image.FromFile("E:\battleship\Explode.gif")
End Sub

Related

Why does a form move trigger ResizeEnd?

I use the following code in my form:
Public Class Form1
Private Sub Form1_ResizeEnd(sender As Object, e As EventArgs) Handles MyBase.ResizeEnd
MsgBox("Resized")
End Sub
End Class
When I move my form, it also seems to trigger MyBase.ResizeEnd. Why is that? A move of the panel doesn't change the size, so I don't understand why.
Why does a form move trigger ResizeEnd?
Because this is the documented behavior. From the documentation:
The ResizeEnd event is also generated after the user moves a form, typically by clicking and dragging on the caption bar.
If you want an event that doesn't get triggered when the form is moved, you should use either Resize or SizeChanged. The problem with those two events is that they will be triggered while the form is being resized by the user. To work around that, you may use it with both ResizeBegin and ResizeEnd with a couple of flags to signal when the user actually finishes resizing the form.
Here's a complete example:
Private _resizeBegin As Boolean
Private _sizeChanged As Boolean
Private Sub Form1_ResizeBegin(sender As Object, e As EventArgs) Handles MyBase.ResizeBegin
_resizeBegin = True
End Sub
Private Sub Form1_SizeChanged(sender As Object, e As EventArgs) Handles MyBase.SizeChanged
' This is to avoid registering this as a resize event if it was triggered
' by another action (e.g., when the form is first initialized).
If Not _resizeBegin Then Exit Sub
_sizeChanged = True
End Sub
Private Sub Form1_ResizeEnd(sender As Object, e As EventArgs) Handles MyBase.ResizeEnd
_resizeBegin = False
If _sizeChanged Then
_sizeChanged = False
MessageBox.Show("The form has been resized.")
End If
End Sub
One thing to note is that both ResizeBegin and ResizeEnd are only triggered when the user manually resizes* the form. It does not, however, handle other situations like when the form is resized via code, when the form is maximized, or restored.
* or moves the form, which is the part that we're trying to avoid here.

Improve UI responsiveness on windows form application

I am currently working on a project and decided to create a user interface for it using visual studio with a windows forms application(Visual Basic).
The problem I'm facing is that the user interface doesn't respond as quickly and smoothly as I'd like it to.
Mainly, I am using pictures as buttons to make the user form look more modern.
However, when I hover my mouse over a "button" it takes a while until the "highlighted button" appears.
P1 is the picture of the "normal button" and P2 is the picture of the "highlighted button".
Here is the short code I have for now:
Public Class Main
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub PictureBox1_MouseHover(sender As Object, e As EventArgs) Handles P1.MouseHover
P1.Visible = False
P2.Visible = True
End Sub
Private Sub P2_MouseClick(sender As Object, e As MouseEventArgs) Handles P2.MouseClick
'Call cmdInit()
'Call cmdConnectRobot()
'Call cmdUnlock()
End Sub
Private Sub Main_MouseHover(sender As Object, e As EventArgs) Handles Me.MouseHover
If P2.Visible = True Then
P2.Visible = False
P1.Visible = True
End If
End Sub
Private Sub P4_Click(sender As Object, e As EventArgs) Handles P4.Click
End Sub
End Class
Another problem I'm facing is that when I call other subs, the user form becomes unresponsive while the sub is running.
I researched and found that I could implement multi threading or async tasks but I'm a bit lost and would be extremely grateful if someone could guide me or point me in the right direction.
Thanks in advance!!
In this case your UI is responsive, however the MouseHover event is only raised once the mouse cursor has hovered over the control for a certain amount of time (default is 400 ms), which is what is causing the delay.
What you are looking for is the MouseEnter event, which is raised as soon as the cursor enters ("touches") the control:
Private Sub P1_MouseEnter(sender As Object, e As EventArgs) Handles P1.MouseEnter
P1.Visible = False
P2.Visible = True
End Sub
You can then use that together with the MouseLeave event on the second picture box to switch back to the non-highlighted image:
Private Sub P2_MouseLeave(sender As Object, e As EventArgs) Handles P2.MouseLeave
P1.Visible = True
P2.Visible = False
End Sub
However switching picture boxes like this is not optimal. I recommend you to look into how you can use Application Resources, then modify your code to only switch the image that one picture box displays.
Here are the basic steps:
Right-click your project in the Solution Explorer and press Properties.
Select the Resources tab.
To add an image either:
a. Drag and drop the image onto the resource pane.
b. Click the arrow next to the Add Resource... button and press Add Existing File....
Now, in your code add this right below Public Class Form1:
Dim ButtonNormal As Image = My.Resources.<first image name>
Dim ButtonHighlighted As Image = My.Resources.<second image name>
Replace <first image name> and <second image name> with the names of your button images.
Now you only need one picture box for the button:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
P1.Image = ButtonNormal
End Sub
Private Sub P1_MouseEnter(sender As System.Object, e As System.EventArgs) Handles P1.MouseEnter
P1.Image = ButtonHighlighted
End Sub
Private Sub P1_MouseLeave(sender As System.Object, e As System.EventArgs) Handles P1.MouseLeave
P1.Image = ButtonNormal
End Sub
I'll start by saying i'm not a programmer by trade, and i'm sure someone will point out better ways of doing these things, but in regards to the threading question it's fairly simple to implement.
Imports System.Threading
Public Class Form1
Dim WorkerThread As New Thread(AddressOf DoWork)
'WorkerThread' can be any name you like, and 'DoWork' is the name of the sub you want to run in the new thread, and is launched by calling:
WorkerThread.start()
However there is a catch, the new thread is not able to interact directly with the GUI, so you cannot change textbox text etc... I find the easiest way to get changes made to the GUI is to drag a timer onto your form, and have the new thread change variables (pre-defined just below Public Class Form1), then use the Timer1 Tick event to monitor the variables and update the GUI if there are any changes.

VB.Net 2015 "Disable btn_MouseLeave on btn_MouseClick"

In VS 2015 Community, My form as a button.
Current Code is:
Private Sub CellStart_MouseHover(sender As Object, e As EventArgs) Handles CellStart.MouseHover
CellStart.BackgroundImage = My.Resources.graycell_hilight
End Sub
Private Sub CellStart_MouseLeave(sender As Object, e As EventArgs) Handles CellStart.MouseLeave
CellStart.BackgroundImage = My.Resources.graycell
End Sub
Private Sub CellStart_Click(sender As Object, e As EventArgs) Handles CellStart.Click
CellStart.BackgroundImage = My.Resources.graycell_select
End Sub
What I want is that if the button is in the post click state (Current BackgroundImage is graycell_select), for the MouseLeave and Mouse Hover to no longer be enabled. If the button becomes deselected I need them to be enabled again. I have tried if statements, assigning an integer +1 on click but nothing seems to override the leave and hover events. I am dreadfully new so any help or points to something similar is appreciated. Thanks in advance. This is in a winform.
Click your button and Find the GotFocus and LostFocus in the Event tab.
Click GotFocus and put this code inside of it.
CellStart.BackgroundImage = My.Resources.graycell_hilight
Click LostFocus and put this code inside of it.
CellStart.BackgroundImage = My.Resources.graycell
leave the click on what it has.
Dont forget to remove not just copy remove the codes in the MouseHover and MouseLeave

loop button to check which was clicked

In VB.net form, I have 20 buttons. They are named from btnLoc1 ~ btnLoc20. I do not want to code each button click event.
How to loop through each button to check which was clicked?
Do I need to implement timer tick to listen for button click event?
You can create a single event handler for all the Buttons. Select all the buttons in the designer, open the Properties window, click the Events button and then double-click the Click event. That will generate a Click event handler, just like when you double-click a Button in the designer, except this one will have multiple items in the Handles clause. You can then use the sender parameter to acces the Button that was clicked, e.g.
Private Sub Buttons_Click(sender As Object, e As EventArgs) Handles Button1.Click,
Button2.Click,
Button3.Click
Dim btn = DirectCast(sender, Button)
'Use btn here.
End Sub
The question then is, what do you want to do with that Button? If you want to do something different for each Button then you really should be creating separate event handlers. Alternatively, you might have a list of data and you want to use the item in that list that corresponds to the Button that was clicked. There are numerous ways to do that. One is to put the data in the Tag property of the Button itself and retrieve it from there. Another is to use concurrent indexes, e.g.
Dim buttons = Controls.OfType(Of Button)().ToArray()
Dim data = {"First", "Second", "Third"}
MessageBox.Show(data(buttons.IndexOf(btn)))
Obviously you need to ensure that the Button array and the data array do line up.
For being noticed if button was clicked - eventhandler is best choice.
But you can create only one eventhandler for all buttons
Private Sub Button_Click(sender As Object, e As EventArgs)
Dim button As Button = DirectCast(sender, Button)
MessageBox($"Button '{button.Name}' was clicked")
End Sub
Then in constructor
Public Sub New()
InitializeComponennts()
AddHandler Button1.Click, AddressOf Me.Button_Click
AddHandler Button2.Click, AddressOf Me.Button_Click
AddHandler Button3.Click, AddressOf Me.Button_Click
' and so on
End Sub
If you want to get information about how much each button was clicked, simply create dictionary and add click amount in one eventhandler
Private ButtonsClickAmount As New Dictionary(Of String, Integer)()
Private Sub Button_Click(sender As Object, e As EventArgs)
Dim button As Button = DirectCast(sender, Button)
If ButtonsClickAmount.ContainKey(button.Name) = True Then
ButtonsClickAmount(button.Name) += 1
Else
ButtonsClickAmount.Add(button.Name, 1)
End If
End Sub

Not fill the grid

Good day,
I have a problem in an MDI form, have the main form, and have 2 buttons, these buttons lead to children forms, one of the forms allows you to select a category from a database, and fills the grid within the, everything works until I I embed the form within the MDI using the button that event is as follows:
Private Sub ButtonCatego_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles ButtonCatego.ItemClick
Dim addCategory As New AddCategory
addCategory.MdiParent = Me.MdiParent
addCategory.Show()
End Sub
When i use the normal event works:
Private Sub ButtonCatego_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles ButtonCatego.ItemClick
AddCategory.Show()
End Sub
Help me please. Thank you
You are setting addCategory.MdiParent to your current form's MDI parent. If Me is your main form then it won't have an MDI parent, which is why you're not getting it to work.
Set addCategory.MdiParent to Me instead and it should resolve your issue:
Private Sub ButtonCatego_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles ButtonCatego.ItemClick
Dim addCategory As New AddCategory()
addCategory.MdiParent = Me
addCategory.Show()
End Sub