How do I create an event on a different form within the VB .NET application for the same device? - vb.net

I'm working on a POS program where I have a POS keyboard COM control within the application. When I double click the icon, an Event is created:
Private Sub PosKeyboard_DataEvent(sender As Object, e As AxOposPOSKeyboard_CCO._IOPOSPOSKeyboardEvents_DataEventEvent) Handles PosKeyboard.DataEvent
If PosKeyboard.POSKeyData = 1 Then Exit_Button.PerformClick()
End Sub**
How do I create an event on a different form within the app for the same device?

Based on the comments so far, I will provide an answer that I think applies.
When it comes to handling events, you have a variable to which you assign an object and then you handle an event of that variable. When the assigned object raises its event, the handling method is executed. So, in your case, you need to start by declaring a variable in the form in which you want to handle the event, e.g.
Private WithEvents posKeyboard As SomeType
The WithEvents keyword is required for that variable to be able to be used in a Handles clause. I use SomeType because I don't know the actual type of your object, although I suspect that it's something like _IOPOSPOSKeyboard.
You can then write a method to handle the desired event, copying the signature from your other form:
Private Sub posKeyboard _DataEvent(sender As Object, e As AxOposPOSKeyboard_CCO._IOPOSPOSKeyboardEvents_DataEventEvent) Handles posKeyboard .DataEvent
'...
End Sub
You then need to pass in the object that will be raising the event from the other form, which you can do via a parameter in a constructor or some other method or a property setter.

Related

Event handlers for object variables VB, VS

Working with a Windows.Forms.Form from the VS designer I can use the KeyDown event when it is fired on a form or on child control (I am interested in RichTextBox). But I want to use the event on a variable type RichTextBox, say:
Dim rtbx as new RichTextBox
Sub rtbx_OnKeyDown(sender as object, e as KeyEventArgs) Handles rtbx.KeyDown
VS does not understand this. There is a method OnKeyDown listed in the ObjectBrowser, which is associated with the grandparent Control class of the RichTextBox, but I have not found any way to call this method. Examples on Microsoft VB documentation show only code looking like one copied from Form.vb class.
There are two ways to attach event handlers in VB. One is to use the WithEvents keyword on a field and the Handles keyword on a method, e.g.
Private WithEvents myRichTextBox As RichTextBox
and:
Private Sub myRichTextBox_KeyDown(sender as object, e as KeyEventArgs) Handles myRichTextBox.KeyDown
That's how it works when you add controls in the designer and then have the IDE generate the event handler. If you look in the designer code file, you'll see a field declared for each control and component you added and each declared WithEvents. If you do that then the event handler remains connected to the field, even if you change the value of the field.
The other option is to use the AddHandler keyword. This is what you must do when attaching an event handler via a local variable, because they obviously cannot be declared WithEvents, e.g.
Private Sub myRichTextBox_KeyDown(sender as object, e as KeyEventArgs)
Note there's no Handles clause on the method. Then:
Dim myRichTextBox As New RichTextBox
'...
AddHandler myRichTextBox.KeyDown, AddressOf myRichTextBox_KeyDown
That event handler will remain attached to the object and, while it is not strictly necessary in some cases, it is good practice to always detach the event handler when you're done with the it:
RemoveHandler myRichTextBox.KeyDown, AddressOf myRichTextBox_KeyDown
You need a reference to the object in order to do that, so you might use a field in order to store that. If there will only be one object, you may as well declare the field WithEvents and use Handles. If there may be multiple objects then you can use a list and then loop through that list to detach the event handlers.

Reference to a non-shared member requires reference

I am updating some code from a vb6 application to VB.NET.
I have a problem that occurs when I try to open a form from the main form.
It calls this function:
Public Sub optDrawSafeFile_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles optDrawSafeFile.CheckedChanged
If eventSender.Checked Then
'--------------------------------------------------------------------------------
' JRL 11-03-06
' change the enables
UpdateGUI((False))
cboProject.SelectedIndex = frmMain.cboProjects.SelectedIndex
SelectJob()
End If
End Sub
And when it goes to execute this line:
cboProject.SelectedIndex = frmMain.cboProjects.SelectedIndex
It blows up and says this:
frmMain is declared like this:
How can I fix this error?
TL;DR
It is described in more detail in this video.
Short answer: change frmMain to My.Forms.frmMain.
cboProject.SelectedIndex = My.Forms.frmMain.cboProjects.SelectedIndex
Long answer:
In VB6, referencing a form by its name allowed you to access it both as a class and an instance of that class. The instance that you access in this manner is called the default instance. This is not possible in VB.NET. However, VB.NET includes a dynamically generated class, My.Forms, that provides functionality similar to that of default instances.
See http://msdn.microsoft.com/en-us/library/ms379610%28v=vs.80%29.aspx#vbmy_topic3 for more information about My.Forms and the "My" namespace.
A better and more object-oriented way to handle this, however, would be to pass the instance of the main form to the constructor of the frmAddMethod form and store it in an instance field.
So, within the class definition in frmAddMethod.vb:
Sub New(ByVal mainForm As frmMain)
_mainForm = mainForm
End Sub
Private _mainForm as frmMain
And when you create the frmAddMethod instance from frmMain, pass in "Me" to the constructor:
Dim addMethodForm as new frmAddMethod(Me)
"Me" is the instance of the class from which a non-shared class method was called.
This will allow you to use the _mainForm class field to access the instance of the main form from non-shared methods of frmAddMethod.
*Edited to recommend My.Forms instead of DefInstance per Plutonix's comment.
Nothing is "blowing up", your program is not crashing. Using a type name, like frmMain, where an object reference is expected is something that the VB.NET compiler allows. Specifically for the Form class, an appcompat hack for VB6 code. It is the debugger that doesn't think much of it. It merely gives you a diagnostic on your watch expression since it doesn't have the same appcompat hack as the compiler does. So doesn't know what to display.
You can use My.Forms instead to get the active form object reference. So make your watch expression:
My.Forms.frmMain.cboProjects.SelectedIndex
Only do this when you are single-stepping the code, it will still go wrong if you use Debug + Break All to break into the program. Setting a watch expression on Me.cboProject is otherwise the obvious workaround in this specific case.

When I call an pre-existing event handler from a subroutine, it doesn't come back. VB

I'm looking to call a pre-existing event handler subroutine from the form_Load event handler.
But the below doesn't work because control doesn't come back and I want to do more.
UPDATE:
I'm new to this so I don't know what the proper protocol is but...
The reason for the non-return was that a statement like the below ended the subroutines execution.
If aLabel.Tag = 1...
the fix was adding New to the declaration to create an instance of it, ie..
changing....
Dim aLabel As Label
... to ...
Dim aLabel As New Label
I'm surprised I didn't get a warning but instead they just abruptly stopped execution of the sub. That wasn't very helpful :)
Thanks again for your time guys...
(Maybe this question should be deleted now that it has served its purpose)
#konrad #karl
END OF UPDATE
What doesn't work is....
Private Sub Form1_Load...
button1_Click(sender, e) 'But Control doesn't come back.
end sub
Do I change the sender to something?
Thanks in advance
Dave
Invoking event handlers like this is a bad idea, because you are trying to simulate the event context by making sender and/or EventArgs be something else.
Instead, put the logic that you want to invoke into a Subroutine or Function and have your Form1_Load method call that; likewise if you really do have a real click event handler, then that handler code can call the method too, like this:
Private Sub Form1_Load()
DoSomeWork()
End Sub
Protected Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
DoSomeWork()
End Sub
Private Sub DoSomeWork()
' Put logic here that you want to do from form load and a button click
End Sub
This has the benefit of making the code cleaner, clearer and easier to maintain as you only need to change the logic in one place should you need to change the logic.
Note: Obviously, you can pass parameters to the DoSomeWork method, if need be, and change it to a Function if you need it to return something.

VB.Net Winform Application based on BackgroundWorker Thread concept - UI update issue

Team,
I have build a VB.Net windows application which does uploads data into database and basically updates two controls:
1. A textbox which is constantly updated with one line per database record upload.
2. A label which keeps track of the count of database record uploaded.
I have used BackgroundWorker thread concept, where the thread's bgwWorker_DoWork() method contains the business logic for upload and bgwWorker_ProgressChanged() updates the 2 UI controls based on uploads.
But the issue I am facing is that I do not get complete updates on both the UI controls. Sometimes the thread bypasses update of textbox and sometimes of label. I could resolve this issue by adding System.Threading.Thread.Sleep(25) before each UI control update code. Is this correct way of solving the issue? OR is there something I am missing?
Kindly suggest.
Below is the code in both these methods:
Private Sub bgwWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgwWorker.DoWork
.................
.................
'Updates database record related update in textbox
System.Threading.Thread.Sleep(25)
updater.eventName = "UpdateStatusBox"
updater.errorMessageToLog = String.Empty
updater.errorMessageToLog += GetErrorMessage(dataTable(rowNumber)("Name").ToString(), ExceptionData)
bgwWorker.ReportProgress(1, updater)
.................
.................
'Updates Status Count in LABEL
System.Threading.Thread.Sleep(25)
updater.eventName = "UpdateStatusBar"
updater.successCount = successCount.ToString()
updater.failureCount = failureCount.ToString()
bgwWorker.ReportProgress(2, updater)
End Sub
Private Sub bgwWorker_ProgressChanged(ByVal sender As System.Object, ByVal e As ProgressChangedEventArgs) Handles bgwWorker.ProgressChanged
Dim updater As UIUpdater = TryCast(e.UserState, UIUpdater)
..........................................
If updater.eventName = "UpdateStatusBar" Then
UpdateStatusBar(updater.successCount, updater.failureCount)
ElseIf updater.eventName = "UpdateStatusBox" Then
txtUpdates.Text = txtUpdates.Text & updater.errorMessageToLog
End If
.....................................
End Sub
I'm almost positive that your problem is your instance of the UIUpdater object called updater. This object appears to be declared globally and is thus shared between calls.
Omitting a little bit of code this is what you have:
updater.eventName = "UpdateStatusBox"
bgwWorker.ReportProgress(1, updater)
updater.eventName = "UpdateStatusBar"
bgwWorker.ReportProgress(2, updater)
Although you call ReportProgress() linearly, it doesn't fire your ProgressChanged event immediately nor does it block until that method completed. To do so would defeat the purpose of threading if you think about it.
To put it another way, you have a global object that you are setting a property on. You then say "when someone gets a chance, do something with this". You then change a property on that global object and sometimes this happens before "someone has done something" happens.
The solution is either to create two global variables, one for each possible event or to just create an instance variable when needed. I'm not sure that its thread safe to use a global variable the way you are so I would recommend just creating an instance variable. In fact, the state object you pass to ReportProgress could just be a string.
I would NOT use a sleep in your DoWork event.
Have you tried refreshing the control after you update it? Each control has a Refresh method which forces a redraw. This may result in flickering though.
Another option is to include the information needed for both controls (textbox and label) in a single call to ReportProgress rather than trying to make two calls.

VB.NET - Passing an event as a parameter

I need to pass an event as a parameter to a function. Is there a way of doing this?
The reason is that I have a sequence of two lines of code that is littered all over my program, where I dynamically remove the handler to an event, and then set the handler again. I'm doing this for several different events and event handlers, so I've decided to write a function that does this.
As an example, let's say I have a combobox in my code called combobox1, and I have the handler called indexChangedHandler. In several places of my code, I have the following two lines:
RemoveHandler combobox1.SelectedIndexChanged, AddressOf indexChangedHandler
AddHandler combobox1.SelectedIndexChanged, AddressOf indexChangedHandler
Now, I don't want to keep on repeating the above two lines of code (or similar) all over my program, so I'm looking for a way to do this:
Private Sub setHandler(evt As Event, hndler As eventhandler)
RemoveHandler evt, hndler
AddHandler evt, hndler
End Sub
so that everywhere where those two lines of code(or similar) occur in my program, I can just replace them with:
setHandler(combobox1.SelectedIndexChanged, AddressOf indexChangedHandler)
So far, the "evt as Event" part of the argument of the setHandler function is giving an error.
P.S: I've asked this question on a couple of other forums and keep getting asked why I would want to set the handler immediately after removing it. The reason is because dynamically adding an event handler n-times causes the handler to be executed n-times when the event occurs. To avoid this, that is, to ensure that the handler is executed just once when the event occurs, I first remove the handler each time I want to add the handler dynamically.
You might be asking why the handler would be added several times in the first place... The reason is because I add the handler only after a particular event, say E1, in my form has occurred (I add the handler within the handler of event E1). And event E1 can occur several times within my form. If I do not remove the handler each time before adding it again, the handler gets added and thus executed several times.
Whatever the case, the processing occurring within the function is not of ultimate importance to me at this time, but rather just the means of passing an event as a parameter.
Of course you can pass events around... Well you can pass Action(Of EventHandler) which can do what you want.
If you have a class that defines an event like so:
Public Class ComboBox
Public Event SelectedIndexChanged As EventHandler
End Class
Given an instance of ComboBox you can then create add & remove handler actions like so:
Dim combobox1 = New ComboBox()
Dim ah As Action(Of EventHandler)
= Sub (h) AddHandler combobox1.SelectedIndexChanged, h
Dim rh As Action(Of EventHandler)
= Sub (h) RemoveHandler combobox1.SelectedIndexChanged, h
(Now, this is VB.NET 4.0 code, but you can do this in 3.5 using AddressOf and a little more mucking about.)
So if I have a handler Foo:
Public Sub Foo(ByVal sender as Object, ByVal e As EventArgs)
Console.WriteLine("Over here with Foo!")
End Sub
And a Raise method on ComboBox I can now do this:
ah(AddressOf Foo)
combobox1.Raise()
rh(AddressOf Foo)
This writes the message "Over here with Foo!" as expected.
I can also create this method:
Public Sub PassActionOfEventHandler(ByVal h As Action(Of EventHandler))
h(AddressOf Foo)
End Sub
I can pass around the event handler actions like so:
PassActionOfEventHandler(ah)
combobox1.Raise()
PassActionOfEventHandler(rh)
Which again writes the message "Over here with Foo!".
Now, one issue that might be a problem is that you can accidentally swap the add and remove event handler delegates in code - after all they are the same type. So it is easy to just define strongly-typed delegates for the add and remove actions like so:
Public Delegate Sub AddHandlerDelegate(Of T)(ByVal eh as T)
Public Delegate Sub RemoveHandlerDelegate(Of T)(ByVal eh as T)
The code to define the delegate instances doesn't change except for the delegate types:
Dim ah As AddHandlerDelegate(Of EventHandler)
= Sub (h) AddHandler combobox1.SelectedIndexChanged, h
Dim rh As RemoveHandlerDelegate(Of EventHandler)
= Sub (h) RemoveHandler combobox1.SelectedIndexChanged, h
So this now lets you be very creative. You can define a function that will take the add handler delegate, the remove handler delegate and a event handler, which will wire-up an event handler, and then return to you an IDisposable that you can use later to remove the handler without needing to retain a reference to the event handler. This is handy for using Using statements.
Here's the signature:
Function SubscribeToEventHandler(
ByVal h as EventHandler,
ByVal ah As AddHandlerDelegate(Of EventHandler),
ByVal rh As RemoveHandlerDelegate(Of EventHandler)) As IDisposable
So given this function I can now do this:
combobox1.Raise()
Using subscription = SubscribeToEventHandler(AddressOf Foo, ah, rh)
combobox1.Raise()
combobox1.Raise()
End Using
combobox1.Raise()
And this writes the message "Over here with Foo!" only twice. The first and last Raise calls are outside of the subscription to the event handler.
Enjoy!
You cannot pass events around. Event isn't a type, it's a keyword that defines a pair of methods, add and remove, used to change the state of the event member of the class. They are very much like properties in this respect (which have get and set methods).
Like properties, the add and remove methods can do whatever you want. Typically, these will do nothing more than maintain a delegate instance, which itself is a MulticastDelegate or in other words, a list of delegates which are getting called one by one if the event is raised.
You can clearly see this structure in C#, where it is not masked with AddHandler/RemoveHandler, but you directly edit the list of associated handlers: myObject.Event += new Delegate(...);.
And, again like properties, being a member of a class that actually abstracts two different methods, it's not possible to literally pass an event as an object.
There are a number of different meanings for the term "event", depending upon context. In the context you are seeking, an Event is a matched pair of methods that will effectively add or remove a delegate from a subscription list. Unfortunately, there's no class in VB.NET to represent a method address without an attached object. One could probably use reflection to fetch the appropriate methods, and then pass those methods to a routine that would call them both, but in your particular situation that would probably be silly.
The only situation where I can see that it might be useful to pass an event in the sense you describe would be for something like an IDisposable object which subscribes to events from longer-lived objects, and which needs to unsubscribe all of its events when it is disposed. In that case, it may be helpful to use reflection to fetch the remove-delegate method for each event, and then call all of the remove-delegate methods when an object is disposed. Unfortunately, I know of no way to represent the events to be retrieved except as string literals, whose validity could not be checked until run-time.