Reacting to third-party application form events using vb.net - vb.net

I would like to know how I should code my VB.net application to react to the form load event in a third-party application (also written in VB.net)
To test, I have created two basic programs, one with two forms (program A) and one (program B) that attempts to the listen to program A's appropriate form load event. I have tried using WithEvents but it does not get fired when Program's A second form loads.
Here is the code for Program A:
Public Class StartPage
Public WithEvents loadtimer As New System.Windows.Forms.Timer
Private Sub StartPage_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
loadtimer.Interval = 1000
loadtimer.Enabled = True
loadtimer.Start()
End Sub
Private Sub loadtimer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles loadtimer.Tick
loadtimer.Stop()
SystemStatus.Show()
End Sub
End Class
Public Class SystemStatus
Inherits StartPage
Private Sub StartPage_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Label1.Text = "This is the form that I want to listen for the load event"
Me.loadtimer.Enabled = False
End Sub
End Class
Here is the code for Program B:
Imports Program_A
Public Class ListeningForm
Dim WithEvents testlisten As New Program_A.SystemStatus
Private Sub testlisten_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles testlisten.Load
Label1.Text = "SystemStatus form loaded"
End Sub
Private Sub ListeningForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Label1.Text = "Waiting for SystemStatus load event..."
End Sub
End Class
I am quite new when it comes to programming so maybe this is not even possible or I just haven't been understanding what I've been reading. In any case please enlighten me as to what my next course of action should be.
Thanks very much in advance,
theoleric

This will do what your asking.
Imports Program_A
Public Class ListeningForm
Dim WithEvents testlisten As New SystemStatus
Private Sub testlisten_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles testlisten.Load
' now this event will fire
Label1.Text = "SystemStatus form loaded"
End Sub
Private Sub ListeningForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Label1.Text = "Waiting for SystemStatus load event..."
' the load event will not fire until you call this
testlisten.Show()
End Sub
End Class

Related

1 contextmenu for 59 labels (MouseDown Events)

i got 59 labels (they describe places in a storage system). With a context menu i want to lock or unlock each of those places for the user.
So in my contextmenu i got two items: Lock and Unlock.
If one label (place) is locked by the user it should send an bit to a plc (but that is not my main problem), and the same for unlock.
Is there any opportunity to do a loop, to find out on which label the contextmenu has been opened? (MouseDown Event)
Here my code so far:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
Me.ContextMenuStrip = ContextMenuStrip1
End Sub
Private Sub Label1_MouseDown(sender As Object, e As MouseEventArgs) Handles Label1.MouseDown, Label2.MouseDown, Label3.MouseDown, Label4.MouseDown, .............. , Label59.MouseDown
ContextMenuStrip1.Tag = sender
End Sub
Private Sub LockToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LockToolStripMenuItem.Click
'send bit to PLC (sender)
End Sub
Private Sub UnlockToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles UnlockToolStripMenuItem.Click
'send bit to PLC (sender)
End Sub
End Class
Sorry for the bad english.

Trouble switching between projects/forms in vb.net

I am working on a project in Visual Studio Community 2019 using VB.Net. I am developing a user interface wherein users start on one form (a sort of index, call it form 1) and select from their the next form they want to go to (say form 2). This part is working fine. The trouble is that after users finish in form 2, they should be directed back to form 1 to continue from here, and I can't get this to happen. I need somehow to make the main menu a public shared form so that the other projects can access it but I can’t figure out how to do that.
Here are the relevant lines from form 1:
Public Class frmMainMenu
Public Shared inst As frmMainMenu
Private Sub frmMenu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
inst = Me
Timer1.Start()
Me.Show()
End Sub
Private Sub BtnGeology_Click(sender As Object, e As EventArgs) Handles
btnGeology.Click
Dim formNew As New Geology.frmGeologyMenu
formNew.Show()
Timer1.Stop()
Me.Hide()
End Sub
And here are the relevant lines from form 2. I want lines 23 and 24 to return the user to the main menu, but it doesn't work.
Public Class frmGeologyMenu
Public Sub frmGeologyMenu_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
lblTime.Text = 10
Me.Show
End Sub
Private Sub BtnMainMenu_Click(sender As Object, e As EventArgs) Handles
btnMainMenu.Click
inst.frmMainMenu.Show()
inst.frmMainMenu.Timer1.Start()
Me.Close()
End Sub
I appreciate any help you can offer!
From my comments above:
When you create your instance of your second form called "formNew",
use the AddHandler command to wire up its FormClosed event to a method
in the main form. Then in the second form you can just call Me.Close()
and the method in the main form will fire where you can call
Me.Show()..
In main menu:
Public Class frmMainMenu
Private Sub BtnGeology_Click(sender As Object, e As EventArgs) Handles btnGeology.Click
Dim formNew As New Geology.frmGeologyMenu
AddHandler formNew.FormClosed, AddressOf formNew_FormClosed
Timer1.Stop()
Me.Hide()
formNew.Show()
End Sub
Private Sub formNew_FormClosed(sender As Object, e As FormClosedEventArgs)
Me.Show()
Timer1.Start()
End Sub
End Class
In frmGeologyMenu:
Public Class frmGeologyMenu
Public Sub frmGeologyMenu_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
lblTime.Text = 10
End Sub
Private Sub BtnMainMenu_Click(sender As Object, e As EventArgs) Handles btnMainMenu.Click
Me.Close()
End Sub
End Class
In VB.NET, your startup form is always the default instance of its type. That means that you can simply use the type name to refer to your startup form anywhere in your app. If you use Me.Hide() in your startup form then frmMainMenu.Show() can be used anywhere to redisplay it. This would not be the case in C# as default form instances are a VB-specific feature. See here for more info.

Passing object as parametar in VB.NET

I am a beginner and please show me how to pass the parameter object Person to Button.Click event. I'm using vb.net. Here is my code:
Public Class Form1
Public Class MyPersonClass
Public Name As String
Public Age As Integer
Public Title As String
End Class
Public Sub DisplayPerson(ByVal person As MyPersonClass)
Label1.Text = person.Name
Label2.Text = person.Age.ToString()
Label3.Text = person.Title
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub
End Class
You don’t – Button1_Click is an event handler, you’re not supposed to call it manually. It gets called, with predefined parameters, when a certain event occurs. You cannot really adapt these parameters, simply because it doesn’t make sense: the event would no longer know how to call the handler.
You can easily write your own method and pass any object to it, of course. And you’ve done exactly that with DisplayPerson.
Private ExamplePerson As MyPerson
Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ExamplePerson = New MyPersonClass 'thanks Chris Dunaway for the correction
ExamplePerson.Name = "Test Name"
ExamplePerson.Age = 36
ExamplePerson.Title = "Title Name"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
DisplayPerson(ExamplePerson)
End Sub

Why does FileSystemWatcher fire twice

why does the FileSystemWatcher fire twice? Is there an easy way to fix it? Surely if I update or edit the text file it should only fire once?
this link here http://weblogs.asp.net/ashben/archive/2003/10/14/31773.aspx says
Events being raised twice - An event will be raised twice if an event handler (AddHander FSW.Created, AddressOf FSW_Created) is
explicitly specified. This is because, by default, the public events
automatically call the respective protected methods (OnChanged,
OnCreated, OnDeleted, OnRenamed). To correct this problem, simply
remove the explicit event handler (AddHandler ...).
What does "remove the explicit event handler" mean?
Imports System.IO
Public Class Form2
Private Sub FileSystemWatcher1_Changed(ByVal sender As System.Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed
'this fires twice
MessageBox.Show("test")
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FileSystemWatcher1.Path = "C:\Users\c\Desktop\test\"
FileSystemWatcher1.NotifyFilter = NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName Or NotifyFilters.CreationTime
FileSystemWatcher1.IncludeSubdirectories = False
FileSystemWatcher1.Filter = "text.txt"
End Sub
End Class
Update:
I have come up with 2 solutions. One uses Threads, and the other doesn't. Take your pick :-).
Without threading:
Imports System.IO
Public Class Form1
Private Sub FileSystemWatcher1_Changed(ByVal sender As System.Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed
Dim watcher As System.IO.FileSystemWatcher = sender
watcher.EnableRaisingEvents = False
'Do work here while new events are not being raised.
MessageBox.Show("Test")
watcher.EnableRaisingEvents = True 'Now we can begin watching for new events.
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FileSystemWatcher1.Path = "C:\Users\c\Desktop\test"
FileSystemWatcher1.NotifyFilter = NotifyFilters.LastWrite
FileSystemWatcher1.IncludeSubdirectories = False
FileSystemWatcher1.Filter = "test.txt"
End Sub
Private Sub FileSystemWatcher_OnChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
End Class
This solution (without threading), sets the watcher.EnableRaisingEvents to False. It is after this point where you would normally process whatever files are affected (or changed). It then sets the EnableRaisingEvents back to True after your work is done.
With threading:
Imports System.IO
Public Class Form1
Private Sub FileSystemWatcher1_Changed(ByVal sender As System.Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed
FileSystemWatcher1.EnableRaisingEvents = False
Threading.Thread.Sleep(250)
FileSystemWatcher1.EnableRaisingEvents = True
MessageBox.Show("test")
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FileSystemWatcher1.Path = "C:\Users\c\Desktop\test"
FileSystemWatcher1.NotifyFilter = NotifyFilters.LastWrite
FileSystemWatcher1.IncludeSubdirectories = False
FileSystemWatcher1.Filter = "test.txt"
End Sub
Private Sub FileSystemWatcher_OnChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
End Class
This solution, although a bit hacky, does work. It disables checking for new changes/events for 250ms and then re-enables checking, based on the assumption that you won't been needing to check for a change every 250ms. I have tried almost everything that I could think of to get a real solution for you but this will work in the meantime.
Check e.ChangeType. I imagine you're getting two different notifications. Perhaps LastAccess and LastModified. In which case, that's the expected behavior.
Today i crashed in FileSystemWatcher and found this site. Suggested Thread.Sleep cannot completely eliminate problem. Tested with fast counter-integer. And is blocking UI. Most problematic is startup, it sliped trough at 5s. Then i set FileSystemWatcher1.EnableRaisingEvents = False immediately in TimerWatcherChanged.Tick and never enabled again... But surprisingly counter still catch up-to 4 events! I would like to share my solution, non-blocking, with adjustable Timer. Feedback is welcome.
Imports System.IO
Imports System.Diagnostics
Public Class Form1
Dim fileName As String
Dim Fsw_counter As Integer
WithEvents TimerWatcherChanged As New Windows.Forms.Timer
WithEvents TimerTest As New Windows.Forms.Timer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TimerWatcherChanged.Interval = 100
TimerTest.Interval = 100 : TimerTest.Start()
TextBox1.Text = "C:\Downloads\New Text Document.txt"
TextBox1.SelectionStart = TextBox1.Text.Length
WatcherSetup()
End Sub
Sub WatcherSetup()
fileName = TextBox1.Text
FileSystemWatcher1.IncludeSubdirectories = False
FileSystemWatcher1.Path = Path.GetDirectoryName(fileName)
FileSystemWatcher1.Filter = Path.GetFileName(fileName)
FileSystemWatcher1.NotifyFilter = NotifyFilters.LastWrite
FileSystemWatcher1.EnableRaisingEvents = True
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
WatcherSetup()
End Sub
Private Sub FileSystemWatcher1_Changed(sender As Object, e As FileSystemEventArgs) Handles FileSystemWatcher1.Changed
If TimerWatcherChanged.Enabled = False Then
TimerWatcherChanged.Enabled = True
Fsw_counter += 1
' ***** Your WATCH Code put here... *****
End If
End Sub
Private Sub TimerWatcherChanged_Tick(sender As Object, e As EventArgs) Handles TimerWatcherChanged.Tick
TimerWatcherChanged.Enabled = False
End Sub
Private Sub TimerTest_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles TimerTest.Tick
TextBox2.Text = "Changed: " & Fsw_counter
If TimerWatcherChanged.Enabled = True Then
TextBox2.BackColor = Color.Red
Else
TextBox2.BackColor = Color.LawnGreen
End If
End Sub
End Class

update form on asynchronous control event

A few weeks ago I wrote a wrapper for the ServiceController control to enhance and streamline the base ServiceController. One of the changes I made was to add a monitoring component using the System.Threading.Timer object. On any change of status, an event is raised to the parent class. The actual monitoring works fine, but when the event is handled in the main form, my program abruptly ends - no exceptions, no warning, it just quits. Here's a skeleton version of the control:
Public Class EnhancedServiceController
Inherits ServiceController
Public Event Stopped(ByVal sender As Object, ByVal e As System.EventArgs)
Public Event Started(ByVal sender As Object, ByVal e As System.EventArgs)
Private _LastStatus As System.ServiceProcess.ServiceControllerStatus
Private serviceCheckTimer as System.Threading.Timer
Private serviceCheckTimerDelegate as System.Threading.TimerCallback
...
Private Sub StartMonitor()
MyBase.Refresh()
_LastStatus = MyBase.Status
serviceCheckTimerDelegate = New System.Threading.TimerCallback(AddressOf CheckStatus)
serviceCheckTimer = New System.Threading.Timer(serviceCheckTimerDelegate, Nothing, 0, 60*1000)
End Sub
Private Sub CheckStatus()
MyBase.Refresh()
Dim s As Integer = MyBase.Status
Select Case s
Case ServiceControllerStatus.Stopped
If Not s = _LastStatus Then
RaiseEvent Stopped(Me, New System.EventArgs)
End If
Case ServiceControllerStatus.Running
If Not s = _LastStatus Then
RaiseEvent Started(Me, New System.EventArgs)
End If
End Select
_LastStatus = s
End Sub
End Class
And the form:
Public Class Form1
Private Sub ServiceStarted(ByVal sender As Object, ByVal e As System.EventArgs) Handles ESC.Started
Me.TextBox1.Text = "STARTED"
End Sub
Private Sub ServiceStopped(ByVal sender As Object, ByVal e As System.EventArgs) Handles ESC.Stopped
Me.TextBox1.Text = "STOPPED"
End Sub
End Class
If I had to guess, I'd say that there's some sort of thread problem, but I'm not sure how to handle that in the form. Any ideas?
IF it is a threading issue then you are probably trying to update the UI from a non-UI thread.
So something like this should solve that...
Private Delegate Sub UpdateTextBoxDelegate(byval tText as String)
Private Sub UpdateTextBox(byval tText As String)
If Me.InvokeRequired Then
Me.Invoke(New UpdateTextBoxDelegate(AddressOf UpdateTextBox), tText)
Exit Sub
End If
TextBox1.Text = tText
End Sub
Private Sub ServiceStarted(ByVal sender As Object, ByVal e As System.EventArgs) Handles ESC.Started
UpdateTextBox ("STARTED")
End Sub
Private Sub ServiceStopped(ByVal sender As Object, ByVal e As System.EventArgs) Handles ESC.Stopped
UpdateTextBox("STOPPED")
End Sub