INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Using Delegates in vb.net

Using Delegates in vb.net

(OP)
Hi,
I recently inherited an sdk written in C# which I managed to translate to vb.net because I'm building a vb.net windows CE app

CODE --> C#

using System;

using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Ekemp
{
    public class DecodeEventArgs : EventArgs
    {
        private string barcode;
        private byte type;

        public DecodeEventArgs(string barcodeData, byte typeData)
        {
            barcode = barcodeData;
            type = typeData;
        }

        public string Barcode
        {
            get { return barcode; }
            set { barcode = value; }
        }

        public byte Type
        {
            get { return type; }
            set { type = value; }
        }

    }

    public class Scanner
    {
        public event EventHandler<DecodeEventArgs> DecodeEvent;

        private bool needClose = false;

        private IntPtr[] hEvent = new IntPtr[2];
        private IntPtr hNotify = IntPtr.Zero;

        private Thread scanThread;

        private bool isContinuousMode;
        public bool IsContinuousMode
        {
            get { return isContinuousMode; }
            set { isContinuousMode = value; }
        }

        public bool Start()
        {

            if (Device.SCA_GetPowerStatus() == 0)
            {
                Device.SCA_EnableModule();
                needClose = true;
            }

            Win32.MSGQUEUEOPTIONS options = new Win32.MSGQUEUEOPTIONS();
            options.dwSize = 20;
            options.dwFlags = 2;
            options.dwMaxMessages = 3;
            options.cbMaxMessage = 252;
            options.bReadAccess = true;

            IntPtr hMsgQ = Win32.CreateMsgQueue(null, options);
            if (hMsgQ == IntPtr.Zero)
            {
                return false;
            }

            hNotify = Device.SCA_RegisterNotification(hMsgQ);
            if (hNotify == IntPtr.Zero)
            {
                return false;
            }

            hEvent[0] = Win32.CreateEvent(IntPtr.Zero, false, false, null);
            hEvent[1] = hMsgQ;

            scanThread = new Thread(new ThreadStart(this.ScanThreadPorc));
            scanThread.Start();

            return true;

        }

        public void Stop()
        {
            try
            {
                Win32.EventModify(hEvent[0], Win32.EVENT_SET);
                if (!scanThread.Join(3000))
                {
                    scanThread.Abort();
                }
            }
            catch (Exception ex)
            {
            }
            Win32.CloseHandle(hEvent[0]);

            Device.SCA_UnRegisterNotification(hNotify);
            Win32.CloseHandle(hEvent[1]);

            if (needClose)
            {
                Device.SCA_DisableModule();
            }
            else  if (isContinuousMode)
            {
                Device.SCA_SetTriggerMode(Device.TriggerMode.Normal);
            }

        }

        public bool SwitchTriggerMode()
        {
            if (isContinuousMode)
            {
                if (Device.SCA_SetTriggerMode(Device.TriggerMode.Normal))
                {
                    isContinuousMode = false;
                    return true;
                }
            }
            else
            {
                if (Device.SCA_SetTriggerMode(Device.TriggerMode.Continuous))
                {
                    isContinuousMode = true;
                    return true;
                }

            }

            return false;
        }


        private void ScanThreadPorc()
        {
            while (true)
            {
                uint evt = Win32.WaitForMultipleObjects(2, hEvent, false, Win32.INFINITE);
                switch (evt)
                {
                    case 0://return thread
                        return;
                    case 1://disable network 
                        uint bytesRead;
                        uint flags;

                        byte[] buf = new byte[256];

                        if (Win32.ReadMsgQueue(hEvent[1], buf, 256, out bytesRead, Win32.INFINITE, out flags))
                        {
                             EventHandler<DecodeEventArgs> temp = DecodeEvent;
                             if (temp != null)
                             {
                                 temp(this, new DecodeEventArgs(Encoding.Default.GetString(buf, 2, (int)bytesRead), buf[1]));
                             }
                        }
                        break;
                }
            }
        }

    }
} 

With the help of some sites I converted to vb.net as:

CODE --> vb.net

Imports System
Imports System.Runtime.InteropServices
Imports System.Collections.Generic
Imports System.Text
Imports System.Threading
Imports ScanDemo
Imports Ekemp


Namespace Ekemp
    Public Class DecodeEventArgs
        Inherits EventArgs
        Public barcode As String
        Public type As Byte

        Public Sub New(ByVal barcodeData As String, ByVal typeData As Byte)
            barcode = barcodeData
            type = typeData
        End Sub

        Public Property pBarcode() As String
            Get
                Return barcode
            End Get
            Set(ByVal value As String)
                barcode = value
            End Set
        End Property

        Public Property pType() As Byte
            Get
                Return type
            End Get
            Set(ByVal value As Byte)
                type = value
            End Set
        End Property
    End Class

    Public Class scann
        Public Event DecodeEvent As EventHandler(Of DecodeEventArgs)
        Private needClose As Boolean = False
        Private hEvent As IntPtr() = New IntPtr(1) {}
        Private hNotify As IntPtr = IntPtr.Zero
        Private scanThread As Thread
        Private m_isContinuousMode As Boolean

        Public Property IsContinuousMode() As Boolean
            Get
                Return m_isContinuousMode
            End Get
            Set(ByVal value As Boolean)
                m_isContinuousMode = value
            End Set
        End Property


        Public Function doStart() As Boolean
            If Device.SCA_GetPowerStatus() = 0 Then
                Device.SCA_EnableModule()
                needClose = True
            End If
            Dim options As Win32.MSGQUEUEOPTIONS = New Win32.MSGQUEUEOPTIONS
            options.dwSize = 20
            options.dwFlags = 2
            options.dwMaxMessages = 3
            options.cbMaxMessage = 252
            options.bReadAccess = True
            Dim hMsgQ As IntPtr = Win32.CreateMsgQueue(String.Empty, options)
            If (hMsgQ = IntPtr.Zero) Then
                Return False
            End If
            hNotify = Device.SCA_RegisterNotification(hMsgQ)
            If (hNotify = IntPtr.Zero) Then
                Return False
            End If
            hEvent(0) = Win32.CreateEvent(IntPtr.Zero, False, False, String.Empty)
            hEvent(1) = hMsgQ
            scanThread = New Thread(New ThreadStart(AddressOf ScanThreadPorc))
            scanThread.Start()
            Return True

        End Function

        Public Sub doStop()
            Try
                Win32.EventModify(hEvent(0), Win32.EVENT_SET)
                If Not (scanThread.Join(3000)) Then
                    scanThread.Abort()
                End If
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Unexpected Error")
            End Try
            Win32.CloseHandle(hEvent(0))
            Device.SCA_UnRegisterNotification(hNotify)
            Win32.CloseHandle(hEvent(1))
            If needClose = True Then
                Device.SCA_DisableModule()
            ElseIf isContinuousMode = True Then
                Device.SCA_SetTriggerMode(Device.TriggerMode.Normal)
            End If
        End Sub

        Public Function SwitchTriggerMode() As Boolean
            If isContinuousMode = True Then
                If Device.SCA_SetTriggerMode(Device.TriggerMode.Normal) Then
                    isContinuousMode = False
                    Return True
                Else
                    If Device.SCA_SetTriggerMode(Device.TriggerMode.Continuous) Then
                        isContinuousMode = True
                        Return True
                    End If
                End If
                Return False
            End If
        End Function
        Private Sub ScanThreadPorc()
            While (True)
                Dim evt As UInteger = Win32.WaitForMultipleObjects(2, hEvent, False, Win32.INFINITE)
                Select Case evt
                    Case 0 '://return thread
                        Return
                    Case 1 '://disable network 
                        Dim bytesRead As UInteger
                        Dim flags As UInteger
                        Dim buf As Byte() = New Byte(255) {}
                        If Win32.ReadMsgQueue(hEvent(1), buf, 256, bytesRead, Win32.INFINITE, flags) Then
                            RaiseEvent DecodeEvent(Me, New DecodeEventArgs(Encoding.[Default].GetString(buf, 2, CInt(bytesRead)), buf(1)))
                        End If
                End Select
            End While
        End Sub
    End Class
End Namespace 

In the sdk their main form has the following code which uses the public class above. I'm struggling to convert it to vb.net especially the 'delegate' part:

CODE --> C#

void scanner_DecodeEvent(object sender, DecodeEventArgs e)
        {
            Win32.sndPlaySound(Properties.Resources.Scan, Win32.SND_ASYNC | Win32.SND_MEMORY);

            this.BeginInvoke((Action<string>)delegate(string barcode)
            {
                scanCount = 0;
                ListViewItem item = new ListViewItem(new string[] { barcode });
                lstView.Items.Insert(0, item);

            }, e.Barcode);
        } 

This is what I have done so far but there are errors on the delegate line:

CODE --> vb.net

Private Sub scanner_DecodeEvent(ByVal sender As Object, ByVal e As DecodeEventArgs)
        PlaySound()
       
        Me.BeginInvoke(DirectCast(Barcode As String) ) 
        scanCount = 0
        Dim item As New ListViewItem(New String() {barcode})

        lstView.Items.Insert(0, item)


    End Sub 

Kindly point me in the right direction in using BeginInvoke to call the delegate. Thanks

RE: Using Delegates in vb.net

You can use auto-implemented properties to clean up the C# => VB conversion of your DecodeEventArgs class

CODE

Public Class DecodeEventArgs
    Inherits EventArgs

    Public Property Barcode As String
    Public Property Type As Byte

    Public Sub New(ByVal barcode As String, ByVal type As Byte)
        Me.Barcode = barcode
        Me.Type = type
    End Sub

End Class 

Then you can use BeginInvoke as follows:

CODE

BeginInvoke(Sub(barcode As String)
                scanCount = 0
                lstView.Items.Insert(0, New ListViewItem(New String() {barcode}))
            End Sub, e.Barcode) 

RE: Using Delegates in vb.net

(OP)
Thanks DaveInIowa,
When I tried the code above I had a error on the Propoerty delacration: saying Pulic Property with a 'Read-Only' or 'Write-only' specifier must have Set and Get.

Thanks

RE: Using Delegates in vb.net

Maybe you're working with an older version of VB.NET that doesn't recognize auto-implemented properties. The reason I included a refactor of the DecodeEventArgs class is because the conversion renamed the Barcode & Type properties to pBarcode & pType. There are other problems also such as making the backing fields public.

RE: Using Delegates in vb.net

Not having your device I haven't tested this, but ....

I've run your c# through one of the converters that I use and the VB is slightly different from yours ......

By the way, you may need to change the Property named Type to [Type], because I think Type is a reserved word.

CODE

Imports System.Threading
Imports System.Text
Imports System.Collections.Generic
Imports System


Namespace Ekemp
	Public Class DecodeEventArgs
		Inherits EventArgs
		Private m_barcode As String
		Private m_type As Byte

		Public Sub New(barcodeData As String, typeData As Byte)
			m_barcode = barcodeData
			m_type = typeData
		End Sub

		Public Property Barcode() As String
			Get
				Return m_barcode
			End Get
			Set
				m_barcode = value
			End Set
		End Property

		Public Property Type() As Byte
			Get
				Return m_type
			End Get
			Set
				m_type = value
			End Set
		End Property

	End Class

	Public Class Scanner
		Public Event DecodeEvent As EventHandler(Of DecodeEventArgs)

		Private needClose As Boolean = False

		Private hEvent As IntPtr() = New IntPtr(1) {}
		Private hNotify As IntPtr = IntPtr.Zero

		Private scanThread As Thread

		Private m_isContinuousMode As Boolean
		Public Property IsContinuousMode() As Boolean
			Get
				Return m_isContinuousMode
			End Get
			Set
				m_isContinuousMode = value
			End Set
		End Property

		Public Function Start() As Boolean

			If Device.SCA_GetPowerStatus() = 0 Then
				Device.SCA_EnableModule()
				needClose = True
			End If

			Dim options As New Win32.MSGQUEUEOPTIONS()
			options.dwSize = 20
			options.dwFlags = 2
			options.dwMaxMessages = 3
			options.cbMaxMessage = 252
			options.bReadAccess = True

			Dim hMsgQ As IntPtr = Win32.CreateMsgQueue(Nothing, options)
			If hMsgQ = IntPtr.Zero Then
				Return False
			End If

			hNotify = Device.SCA_RegisterNotification(hMsgQ)
			If hNotify = IntPtr.Zero Then
				Return False
			End If

			hEvent(0) = Win32.CreateEvent(IntPtr.Zero, False, False, Nothing)
			hEvent(1) = hMsgQ

			scanThread = New Thread(New ThreadStart(Me.ScanThreadPorc))
			scanThread.Start()

			Return True

		End Function

		Public Sub [Stop]()
			Try
				Win32.EventModify(hEvent(0), Win32.EVENT_SET)
				If Not scanThread.Join(3000) Then
					scanThread.Abort()
				End If
			Catch ex As Exception
			End Try
			Win32.CloseHandle(hEvent(0))

			Device.SCA_UnRegisterNotification(hNotify)
			Win32.CloseHandle(hEvent(1))

			If needClose Then
				Device.SCA_DisableModule()
			ElseIf m_isContinuousMode Then
				Device.SCA_SetTriggerMode(Device.TriggerMode.Normal)
			End If

		End Sub

		Public Function SwitchTriggerMode() As Boolean
			If m_isContinuousMode Then
				If Device.SCA_SetTriggerMode(Device.TriggerMode.Normal) Then
					m_isContinuousMode = False
					Return True
				End If
			Else
				If Device.SCA_SetTriggerMode(Device.TriggerMode.Continuous) Then
					m_isContinuousMode = True
					Return True

				End If
			End If

			Return False
		End Function


		Private Sub ScanThreadPorc()
			While True
				Dim evt As UInteger = Win32.WaitForMultipleObjects(2, hEvent, False, Win32.INFINITE)
				Select Case evt
					Case 0
						'return thread
						Return
					Case 1
						'disable network 
						Dim bytesRead As UInteger
						Dim flags As UInteger

						Dim buf As Byte() = New Byte(255) {}

						If Win32.ReadMsgQueue(hEvent(1), buf, 256, bytesRead, Win32.INFINITE, flags) Then
							Dim temp As EventHandler(Of DecodeEventArgs) = DecodeEvent
							If temp IsNot Nothing Then
								temp(Me, New DecodeEventArgs(Encoding.[Default].GetString(buf, 2, CType(bytesRead, Integer)), buf(1)))
							End If
						End If
						Exit Select
				End Select
			End While
		End Sub

	End Class
End Namespace 

CODE

Private Sub scanner_DecodeEvent(sender As Object, e As DecodeEventArgs)
	Win32.sndPlaySound(Properties.Resources.Scan, Win32.SND_ASYNC Or Win32.SND_MEMORY)

	Me.BeginInvoke(CType(Sub(barcode As String) 
	scanCount = 0
	Dim item As New ListViewItem(New String() {barcode})

	lstView.Items.Insert(0, item)
        End Sub, Action(Of String)), e.Barcode)
End Sub 

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close