c# event handler fires an event

  • Thread starter Thread starter Dan Bass
  • Start date Start date
D

Dan Bass

I'm writing a scanner application (C# / .Net CF) where I have one scanner
object (singleton) that hooks into the scan engine drivers.

There is scanner event for a successful scan, that passes through the
scanned data to an event handler. From here I need to pass this information
back to my form, so what I've done is to create another event handler in the
form, which is fired from the event handler in my scanner class.

The Form declaration of this object looks like this:

Is this ok?
Is this considered good practice or is there a blatantly obvious and much
better way of doing this?

Below is the code that's relevant:

// ----------------------------------------------------------
//
// myForm snippet
//

ScanEngine scanner;

private void myForm_Load(object sender, System.EventArgs e)
{
scanner = new ScanEngine();
scanner.StartScan();
scanner.Scanned += new EventHandler(BarcodeRead);
}

private void FormPut_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
if ( scanner != null )
{
scanner.StopScan();
scanner.Scanned -= new EventHandler(BarcodeRead);
scanner = null;
}
}

void BarcodeRead(object sender, System.EventArgs e)
{
if ( scanner != null )
{
string barData = scanner.BarcodeData;

// do stuff here

}
}

// ----------------------------------------------------------
//
// ScanEngine snippet
//


private string barData = "";
public event System.EventHandler Scanned;

// called when a scan occurs
protected virtual void OnScanned(EventArgs e)
{
if (Scanned != null)
Scanned(this, e);
}

public string BarcodeData
{
get
{
return barData;
}
}
 
You should declare your own delegate type, something like that:

public delegate void ScannedEventHandler(object sender, string barcodeData);

and then in your ScanEngine class you'd declare your event as

public event ScannedEventHandler Scanned;

HTH... Alex
 
Expanding on this deriving from System.EventArgs will give you the
opportunity to store the scanned data in the event argument thus:

public class ScannerArgs : System.EventArgs

{

public readonly string Data;

public ResponseArgs(string data)

{

this.data = data;

}

}

public delegate void ScannedEventHandler(object sender, ScannerArgs scan);

so now in your event hander you can access the data via the event object
using e.Data
 
If the scan engine runs on a worker thread you might also consider
marshaling the event back to the primary UI thread in your private handler
through Invoke so that the application consumer of the public event can
directly affect UI elements.
 
To be honest, I'm not sure.

How would I check whether it is on the main thread or on a seperate thread?

I update the UI from the result of this scan event, so does this mean that
it is on the UI thread or just that my programming is bad practiced because
I'm not sure?

Thanks for your help.
 
Back
Top