How to make a mousemove event for multiple labels with one sub procedure? - vb.net

I have the following code for a project I'm working in class and I need to copy it about 9 times in total. the only thing that will change each time is the category number and the label name by 1. Do I HAVE to create a mousemove event inidividually for each or is there a way to do it in one sub procedure? I don't care if it is harder, or less efficient I would just like to see if it is possible and how. Thank you.
Private Sub lbl1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lbl1.MouseMove
category = 1
scoreRoll()
lbl1.Text = score
End Sub
It has been said this may be a duplicate. If someone could tell me how to do that same thing with mousemove instead of click that would be perfect. Thank you.

Multiple controls can share the same event. You just need to check the sender variable to see which one it was and process appropriately:
Private Sub lbl_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lbl1.MouseMove, lbl2.MouseMove, lbl3.MouseMove, lbl4.MouseMove, lbl5.MouseMove, lbl6.MouseMove, lbl7.MouseMove, lbl8.MouseMove, lbl9.MouseMove
Dim lbl As Label = CType(sender, Label)
category = CInt(lbl.Name.Replace("lbl", ""))
scoreRoll()
lbl.Text = score
End Sub

Related

How to share events between forms

So i have a tray icon that should behave the same way between 3 forms. I then created this code:
Private Sub TrayForm_MouseClick(sender As Object, e As MouseEventArgs) Handles NotifyIcon1.MouseClick
If e.Button = MouseButtons.Right Then
If Not Application.OpenForms().OfType(Of TrayForm).Any = 1 Then
TrayForm.ContextMenuStrip1.Show(Cursor.Position)
End If
End If
End Sub
Which is used to handle the tray icon. How can i do to share this event between the forms so i don't have to place this same code on every form?
How are event handlers working exactly? I looked online and on MSDN and it is not clear to me.
Thanks
Are you sure that you want to share the event, and not juste the code that will handle the event?
If you don't want to copy and paste your code, which you need to handle the events of more than one form, here's a way to do it:
Declare the sub which contains the code needed to handle the event as a public shared sub. Like this:
Public Shared Sub TrayForm_MouseClick(sender As Object, e As MouseEventArgs)
So, now you have a Sub which can handle the event you want to handle from all three forms.
Now, when you initialize those forms, add a line to make the shared Sub handle the event you want it to handle:
AddHandler NotifyIcon1.MouseClick, AddressOf ProjectName.FileName.TrayForm_MouseClick
ProjectName.FileName is meant here to be the path to refer to the shares Sub inside the file where you put it. I usually name it like ProjectNameUtils.vb or something like that.
If you just want to avoid copy and pasting your Sub so you don't have to modify it at several places every time you change something, this could be a way to achieve that.
As Stipulated by Hans Passant:
Sub Eclass_EventHandler(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
If e.Button = MouseButtons.Right Then
If Not Application.OpenForms().OfType(Of TrayForm).Any = 1 Then
Me.ContextMenuStrip1.Show(Cursor.Position)
End If
End If
End Sub
On the Trayform.VB just did the trick.
But about the shared event. i Have one that would have to be:
Private Sub FormClosingEVENT(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
If Not FromMenu Then e.Cancel = True
Me.WindowState = FormWindowState.Minimized
'Application.Exit()
End Sub
How should i handle this?

Creating a way to handle textbox validation

I have a time entry form that contains a tabcontrol with tab pages for each day of the week. Within this control is a table layout panel that is holding together various textboxes/labels. For each day of the week, the inputs are named in a similar fashion:
txtMonWorkHours
txtMonPTOHours
txtMonOTHours
txtTuesWorkHours
txtTuesPTOHours
txtTuesOTHours
...
I am using ADO.net to load/save all these values from a database into their respective textboxes.
What I am now trying to do now is provide a method to validate entry (which I have now finished on an individual event basis such as:
Private Sub txtMonIn_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtMonIn.Leave
ValidateTimeEntered(txtMonIn)
End Sub
and
Private Sub txtMonIn_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMonIn.TextChanged
TransitionTextPreValidate(txtMonIn)
End Sub
My question is: Is there a way to add the method I have created to all the textboxes I need without having to assign each method to each textbox event individually?
Your events have the ability to handle multiple controls, that is why the "sender" object is passed, so you know who is calling the event. Try this, notice the end of the sub's declaration:
Private Sub txtWeekdayIn_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtMonIn.Leave, txtTueIn.Leave, txtWedIn.Leave
ValidateTimeEntered(sender)
End Sub

How to wait for line of code to finish before moving onto the next line

I'm using Visual Basic 2010, and within my form shown sub I need two buttons to be pressed , however I need the first button's code to complete before the moving on to pressing the next button. Is there any way to allow this to happen? Thanks :)
Private Sub Form1_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
BindingNavigatorMoveLastItem.PerformClick()))
'I need this next button click to be carried out after the one above has completely finished
BindingNavigatorMovePreviousItem.PerformClick()))
End Sub
Use methods instead of "button-clicks":
Private Sub Form1_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
MoveLastItem()
MovePreviousItem()
End Sub
Private Sub MoveLastItem()
bindingSource1.MoveLast();
End Sub
Private Sub MovePreviousItem()
bindingSource1.MovePrevious();
End Sub
You just have call these methods from the button-click events handlers as well.
Private Sub BindingNavigatorMoveLastItem_Clicked(sender As Object, args As EventArgs) Handles BindingNavigatorMoveLastItem.Click
MoveLastItem()
End Sub
Private Sub BindingNavigatorMovePreviousItem_Clicked(sender As Object, args As EventArgs) Handles BindingNavigatorMovePreviousItem.Click
MovePreviousItem()
End Sub
I must admit I don't do VB, but I came across this page and it might be useful to you.
http://msdn.microsoft.com/en-us//library/system.windows.forms.application.doevents.aspx
If that is not relevant, in your situation I would either use the buttons to set flags and simply if-test the flags, or create a do-while loop so that the code can finish executing while the conditions are met. Careful with those, however, as infinite loops are something they are good at.
Another thought is to enable the second button in the last line of the code of the first button?
Hope something helps. Apologies if it is of no use.

Form_Load doesn't execute in application

I am new to Visual Basic. I have installed Microsoft Visual Studio 2010. Created a new Windows Form Application. As an example, I made a simple program which will ask the end user to input 2 numbers and allow them to either add them or subtract the second number from the first one and display the output in a Textbox.
Now, I added another Subroutine which would be executed automatically when the Windows Form loads. This would calculate the width of the output Textbox and the Form Width and display at the bottom.
This is how the code looks like right now:
Public Class Form1
' Run this Subroutine initially to display the Form and Text box width
Private Sub Form_Load()
Label5.Text = TextBox3.Width
Label7.Text = Me.Width
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim a As Integer
Dim b As Integer
a = TextBox1.Text
b = TextBox2.Text
TextBox3.Text = a + b
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim a As Integer
Dim b As Integer
a = TextBox1.Text
b = TextBox2.Text
TextBox3.Text = a - b
End Sub
End Class
While everything works correctly for the addition and subtraction, it does not display the Form and output Textbox width in the Windows Form.
I think, Form_Load() is not executing properly.
I also tried, Form_Activate() but that did not work either.
Once I am able to do this, I would like to extend this concept to resize the output Textbox along with the Form resize. However, for the purpose of understanding I wanted to see if I can execute Form_Load() successfully.
Thanks.
Form_Load doesn’t execute. For now, it’s just any other method. In order to tell VB to make this method handle the Load event, you need to tell it so:
Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Loasd
Label5.Text = TextBox3.Width
Label7.Text = Me.Width
End Sub
(And add the required parameters for the event.)
A few other remarks:
Ensure that Option Strict On is enabled in your project options at all times. This will make the compiler much stricter with your code and flag more errors. This is a good thing since these errors are potential bugs. In particular, your code is very lax with conversions between different data types, these should be made explicit.
Initialise variables when you declare them, don’t assign a value in a separate statement. That is, write this:
Dim a As Integer = Integer.Parse(TextBox1.Text)
(Explicit conversion added as well.)
If you want to make a control fill the form, you can just set its Dock property appropriately in the forms editor, instead of having to program this manually.
You need to add the Handle so the app executes it automatically:
Private Sub Form_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
'...
End Sub

Text is selected in the text box

When I load the form where some text has been given to text box. All the text in that textbox is highlighted. I want vb not to load it this way.
How to fix it.
Thanks
Furqna
You could set the tab index on your textbox to something else so that it's not the lowest index.
You could set the TextBox1.SelectionLength = 0 in the form.activated event.
I don't like this as much because if the user had the text hilited and minized the application then they will lose the hilite, but is fairly easy to do. I guess you could use a flag to make sure it only did it on the first activate.
You could set a timer event in the load to clear it immediately after the load event, but that seems like overkill. I have worked at places where they had a standard function that happened on every form 100 ms after load because of problems such as this.
You could try this(it looks like a workaround):
Private Sub TextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus
TextBox1.SelectionStart = TextBox1.Text.Length
End Sub
It depends on the TabIndex of your TextBox, if it has the lowest TabIndex it gets focus and therefore it's Text is selected.
' VS.net 2013. Use the "Shown" event.
' GotFocus isn't soon enough.
Private Sub Form_Shown(sender As Object, e As EventArgs) Handles Me.Shown
TB.SelectionLength = 0
End Sub
Type 1 Method
Dim speech = CreateObject("sapi.spvoice")
speech.speak(TextBox1.Text)
Type 2 Method
Dim oVoice As New SpeechLib.SpVoice
Dim cpFileStream As New SpeechLib.SpFileStream
'Set the voice type male or female and etc
oVoice.Voice = oVoice.GetVoices.Item(0)
'Set the voice volume
oVoice.Volume = 100
'Set the text that will be read by computer
oVoice.Speak(TextBox1.Text, SpeechLib.SpeechVoiceSpeakFlags.SVSFDefault)
oVoice = Nothing
Type 3 Method
Imports System.Speech.Synthesis
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim spk As New SpeechSynthesizer
For Each voice As InstalledVoice In spk.GetInstalledVoices
ListBox1.Items.Add(voice.VoiceInfo.Name)
Next
ListBox1.SelectedIndex = 0
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim spk As New SpeechSynthesizer
spk.SelectVoice(ListBox1.SelectedItem.ToString)
spk.Speak(TextBox1.Text)
End Sub
End Class
This will also happen sometimes if The TextChanged or other similar Event is fired twice for the control.
When creating each form. Each object is indexed you can set the tab Index higher then the indexed object. Example: On the third form you put a text box in.
private void textBox1_TextChanged(object sender, EventArgs e)
This was the 12th object in the project, it would be indexed at 12. if you put the tab index higher then the indexed objects throughout the project. Tab index 1000 (problem solved.)
Have a great day.
Scooter