Accessing a custom DLL

I put this together to read from a set of pallet wrapping scales that we have. Activated from a button click, but had to do some dancing around with event handlers or listeners rather than all of the code being on a button click:

using System.IO.Ports;

public class Script
{
	// ** Wizard Insert Location - Do Not Remove 'Begin/End Wizard Added Module Level Variables' Comments! **
	// Begin Wizard Added Module Level Variables **
	// End Wizard Added Module Level Variables **

	// Add Custom Module Level Variables Here **
	SerialPort _serialPort = new SerialPort("COM11", 9600, Parity.None, 8, StopBits.One); 

	public void InitializeCustomCode()
	{
		// ** Wizard Insert Location - Do not delete 'Begin/End Wizard Added Variable Initialization' lines **
		// Begin Wizard Added Variable Initialization
		// End Wizard Added Variable Initialization

		// Begin Wizard Added Custom Method Calls
			this.btnWeigh.Click += new System.EventHandler(this.btnWeigh_Click);
		// End Wizard Added Custom Method Calls

			_serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);


	}

	public void DestroyCustomCode()
	{
		// ** Wizard Insert Location - Do not delete 'Begin/End Wizard Added Object Disposal' lines **
		// Begin Wizard Added Object Disposal

			this.btnWeigh.Click -= new System.EventHandler(this.btnWeigh_Click);

		// End Wizard Added Object Disposal

		// Begin Custom Code Disposal

			_serialPort.Dispose() ;
			_serialPort = null ;
			_serialPort.DataReceived -= new SerialDataReceivedEventHandler(sp_DataReceived);

		// End Custom Code Disposal
	}
                
	private delegate void SetTextDeleg(string text);
                
	private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
	{              
		string data = _serialPort.ReadLine(); 
		double weight = Convert.ToDouble(data.Substring(6, 8));

		numActWeight.Value = weight;

		try
		{ 
			if(_serialPort.IsOpen) 
			_serialPort.Close(); 
		}
		catch(UnauthorizedAccessException ex)
		{
			MessageBox.Show(ex.Message);
		}              
	}

	private void si_DataReceived(string data) { numActWeight.Value = data.Trim(); } 

	private void btnWeigh_Click(object sender, System.EventArgs args)
	{
		_serialPort.WriteTimeout = 500; 

		try
		{ 
			if(!(_serialPort.IsOpen)) 

			_serialPort.Open(); 

			//_serialPort.Write("READ\r\n"); 
			_serialPort.Write("GR10\r\n");    // Added by MD - get decimal places from scale
		} 
		catch (Exception ex)
		{ 
			MessageBox.Show("Error opening/writing to serial port :: " + ex.Message, "Error!"); 
		} 
	}            
 

}


1 Like