OnRead event from scanner (Motorla EMDK) fires continuously - vb.net

(I'm using VS2008 with EMDK v2.9 with Fix1)
I have a form, where I declare my reader:
Private WithEvents barcodeReader As Barcode.Barcode = New Barcode.Barcode
I want it to be active only in one of the controls on the form, so I do this:
Private Sub txbAccount_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txbAccount.GotFocus
barcodeReader.EnableScanner = True
End Sub
And turn it off the same way in the Lost Focus event of that textbox.
Here is the OnRead sub:
Private Sub barcodeReader_OnRead(ByVal sender As Object, ByVal readerData as Symbol.Barcode.ReaderData) Handles barcodeReader.OnRead
If (readerData.HasReader) Then
Try
Dim ctrl As TextBox = Ctype(GetActiveControl(), TextBox)
If (ctrl.Name = "txbAccount") Then
ctrl.Text = readerData.Text
End If
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
End If
End Sub
The problem is: as soon as I enable scanner in the GotFocus event of the textbox, the OnRead event will fire over and over (with empty data) until I actually press the scan key, scan actual data - then it stops.
I've read that maybe the Handled property is not getting set properly, however I don't see property like that for this.

Quick question to answer is the handledis usualy within the e eventargs (although I dont see any in that routine just readerdata it may be in there!?
On a side, with barcode scanners they usualy use the sendkeys commands to simply pass string through to the system. These can be trapped easily by using any of the OnKeyPress / OnKeyDown... etc. If you wanted to go down this route, you'll need to take each keypress / down as aan individual character, whereas your barcode.OnRead might do all that for you. (Again I havent used the EMDK you reference).
Lastly 'usualy' barcode scanners end with a cr (carriage return) some barcode scanners can turn this off, or change these in settings. If not this might be where the e.handled referenced elsewhere is talking about. This would be something like ..
if e.KeyChar = Chr(Keys.Enter) then
e.handled = true
end if
This would stop the send going to the object (textbox) and therfore not losing focus (as the enter key wasn't passed)
Hope this helps.. a bit :)
Chicken

Related

How do i detect Alt + Tab Key and then close the form?

I want to close my form when Alt + Tab is pressed. However, The form is somehow not registering the key combination.
i have tried to use the Me.KeyUp event to detect the keys
Private Sub Menu_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
Select Case e.KeyData
Case (Keys.Alt + Keys.Tab)
Close()
End Select
End Sub
How can it be done ?
Try this: As in my comment Alt+Tab would not work. So try something else like Alt+Q. Put this code under the Form's keydown event.
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
If (e.KeyCode = Keys.Q AndAlso e.Modifiers = Keys.Alt) Then
Me.Close()
End If
End Sub
You need to set the form's Set KeyPreview to True for it to respond to the key events, but since Alt + Tab is a special windows combination the key events will not be fired.
Try in this way
Dim myval As Integer 'this is global variable declare
Private Sub Menu_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
Select Case e.KeyData
Case (Keys.Alt)
myval = 1
Case (Keys.Tab)
If myval = 1 Then
Me.Close()
End If
End Select
End Sub
May be my syntax in not correct, please edit it if anything is notok.
I managed to work around this problem using this method-
That's usually the ESC key. One key press. A common one. Maybe you want to handle the Form's deactivate event, instead. – Jimi
I used the forms deactivate event to close it, since Alt+Tab is basically deactivating the form!
(A workaround because Alt+Tab as keystrokes were not detected by any means, as mentioned by
the last two answers.)
My final code looks like this -
Private Sub Menu_Deactivate(sender As Object, e As EventArgs) Handles Me.Deactivate
If loaded = true Then
Close()
End If
End Sub
I had to check if loaded (a boolean i declared to be set to true when everything is loaded)
to be true because my form opens one other form while loading, which inadvertently deactivated the main form and closed it!
Thank you so much for helping me everyone!!
Edit: I needed to clarify that the second form is always behind my main form so it is never really clicked on. I did this as a workaround to have aero blur in my application without a bug i experienced while applying it to the main form - it is too light, so text is unreadable. So i set another form to show aero blur and always stay behind my main form, whose opacity I have set to 0.88. This gives me a lot of control over the look of the blur.

handled is not a member of Eventargs

I inherited this vb.net code and am a newbie vb.net programmer with old programming skills.
This problem exists in many places after calling a dialog box. After processing the dialog, if the enter key is pressed on the dialog instead of clicking OK, the enter key logic is then processed on the main form. This is undesirable and i need to just display the form.
It looks like "e.handled = True" may be the way to clear the key results, but it produces the "handled is not a member of Eventargs" error.
Can you please recommend the best way to handle this situation?
Thank You,
Brian
Private Sub mnuAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAbout.Click
Try
'Get the menu off of the screen cleanly
Application.DoEvents()
dlgAbout.ShowDialog()
**e.handled = True**
Catch ex As Exception
Call modErrorHandler.ErrorProcedure(ex.GetType.Name, Me.Name, ex.Message, ExceptionClassName(ex), ExceptionMethodName(ex), ExceptionLineNumber(ex))
End Try
End Sub

How to put received serial text into multiple text boxes?

I am doing a serial communication project and would like to have the received string go into a text box based on which button was clicked to send the initial string and invoke a response.
The code for the ReceivedText is:
PrivateSub ReceivedText(ByVal [text] As String)
Button1.Clear()
Button2.Clear()
If Button1.InvokeRequired Then
RichTextBox1.text = [text].Trim("!")
End If
If Button2.InvokeRequired Then
RichTextBox2.Text = [text].Trim("!")
End If
EndSub
This just results in the received string going into both of the boxes instead of one or the other.
Is there any way to get the text to go in the appropriate box?
The key to remember is that .Net treats all serial comm as threads. Let me give you a simple example of updating textboxes from one of my programs that reads data from a scale.
Private Sub ComScale_DataReceived(sender As System.Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles ComScale.DataReceived
If ComScale.IsOpen Then
Try
' read entire string until .Newline
readScaleBuffer = ComScale.ReadLine()
'data to UI thread because you can't update the GUI here
Me.BeginInvoke(New EventHandler(AddressOf DoScaleUpdate))
Catch ex As Exception : err(ex.ToString)
End Try
End If
End Sub
You'll note a routine DoScaleUpdate is invoked which does the GUI stuff:
Public Sub DoScaleUpdate(ByVal sender As Object, ByVal e As System.EventArgs)
Try
'getAveryWgt just parses what was read into something like this {"20.90", "LB", "GROSS"}
Dim rst() As String = getAveryWgt(readScaleBuffer)
txtWgt.Text = rst(0)
txtUom.Text = rst(1)
txttype.Text = rst(2)
Catch ex As Exception : err(ex.ToString)
End Try
End Sub
You CAN make it much more complicated if you choose (see post #15 of this thread for an example) but this should be enough to do what you need.

VB.NET Events not Firing

I've received a project from another developer. Long story short, the program pulls several thousand entries from an SQL Database hosted on our internal network. The program displays the entries and allows you to filter them for convenience.
Recently we had an issue in which a table in our SQL Database was cleared (It's normally regenerated each day, but for several days it was blank.) Found the issue and solved it (Made no changes to the VB project) to repopulate the table; but since that point the VB project would no longer fire events.
The program is several thousand lines of code long, so I can not post the entire thing; but I will try my best to give symptoms:
The form object can fire events (Form_Closing, Form_Closed, etc.)
The existing controls (Radio button, buttons, picturebox, data grid view, etc) will not fire any events.
If I add a new control (such as a button), it will not fire events.
If a put a debug breakpoint at the sub that should be fired, it will not break.
Here's an example of a method that should be fired but is not fired:
`Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsgBox("GOT IT!")
End Sub`
Here's the Form_Load sub:
<DllImport("user32.dll")> _
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitializeComponent()
Try
DataGridView_Items.RowsDefaultCellStyle.SelectionBackColor = Color.Yellow
DataGridView_Items.RowsDefaultCellStyle.SelectionForeColor = Color.Black
CheckBox_Highlight.DataBindings.Add("Visible", RadioButton_BD, "Checked")
Try
'Populates the DGV
LoadTable()
TableLayoutPanel_BD_Parts.Visible = True
TableLayoutPanel_PF_Parts.Visible = False
'Exits if no data was pulled from the database
If dbDataSet.Rows.Count = 0 Or pfDataSet.Rows.Count = 0 Then Application.ExitThread()
Catch ex As Exception
Using w As StreamWriter = File.AppendText(logFile)
Log("Function Form1_Load says " & ex.Message & " # " & DateTime.Now.ToString("yyyy-MM-dd") & "_" & DateTime.Now.ToString("HH-mm-ss"), w)
End Using
End Try
BackgroundWorker1.RunWorkerAsync()
formLoaded = True
Catch exx As Exception
MsgBox(exx.ToString())
End Try
End Sub
There is a backgroundworker, but it appears to work correctly and exit out.
All the forms can be interacted with; but do not fire events. (I can change the selection of the radio button, click the button, type into text boxes, etc.)
I know this is a little vague, I'm just hoping someone can give suggestions as to things that could cause this that I can look into. I can provide specifics; but I can't copy the entire code here.
Thanks for any help!
A very strange thing in your code is that you call InitializeComponent() from Form_Load.
Usually this method is called in Form constructor so you can remove it from Form_Load.
I made some test on my PC: if you called twice InitializeComponent() you duplicate every controls in the form and their events doesn't fire anymore maybe because you have two controls with the same name.

Not checking for control key pressed properly

I got this timer tick function:
Private Sub controlTick(ByVal sender As Object, ByVal e As EventArgs)
Label2.Text = (Control.ModifierKeys = Keys.Control)
End Sub
That is supposed to make my label say "True" if I am currently holding down the Control key, and "False" if I am not.
But, how come my label is always "False"? What is interesting is that if I press the Control key at lighting speed a bunch of times I can see for a fraction of a second "True", but immediately turns to "False".
Timer ticks every 50ms.
I do not understand.... any ideas?
I can't reproduce the behavior you describe... I tried creating a new WinForms project, placed a Label control on the middle of the form, and added a Timer control.
Whenever I press the Ctrl key, the label reads True. Otherwise, it reads False. Exactly the behavior you would expect to see. I don't have to press anything at lightning speed.
(Edit: It doesn't break when more controls are placed on the form either. What are you doing differently?)
My code looks like this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
' Start the timer
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
' Update the label
Label1.Text = (Control.ModifierKeys = Keys.Control).ToString
End Sub
Only difference is that you're apparently compiling without type checking enabled (Option Strict Off).
I always prefer to code in VB.NET with this turned on (check your project's Properties window), in which case you have to explicitly convert the boolean type to a string type using ToString.
I have created a winform application to prove this.. I am using the form and I have set the "KeyPreview" property to true and for every key pressed I get the code correctly.
Please check again using the way I mentioned and let me know if it resolves.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show(e.KeyCode.ToString());
}
Also for Control key the code is (e.KeyCode == Keys.ControlKey)....
I'm not sure this will help, but try using HasFlag, because maybe there is some other flag in ModifierKeys which is also on:
http://msdn.microsoft.com/en-us/library/system.enum.hasflag.aspx