Windows Form application on WinCe 6 - c#

I am building a simple Windows Forms Application.
It is very simple,on my Windows PC, it runs without any problems.
If I try to copy the .exe and .pdb file on my Windows Ce device and try to start it, I get this error:
File or assembly name
'System.windows.forms, Version= 2.0.0.0, Culture=neutral, PublickKeyToke= ..... or one of its dependecies, was not found.
My application has two simple textboxes and writes a text in a .txt file. This is the code of Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace EasyManagementOrdine
{
public partial class Form1 : Form
{
private const string FILE_NAME = "ESPORTAZIONE.txt";
public List<string> listaString = new List<string>();
public StreamWriter sw;
public Form1()
{
try
{
InitializeComponent();
if (File.Exists("ESPORTAZIONE.txt"))
{
File.Delete("ESPORTAZIONE.txt");
}
this.sw = File.CreateText("ESPORTAZIONE.txt");
//this.textQuantita.KeyPress.(new KeyPressEventHandler(this, CheckEnter));
this.textCodiceBarre.Focus();
}
catch(Exception e)
{
}
}
private void codiceBarreEnter(object sender, KeyPressEventArgs e)
{
try
{
if (e.KeyChar == '\r')
{
if ((!this.textCodiceBarre.Focused ? false : this.textCodiceBarre.Text.Length > 0))
{
this.textQuantita.Focus();
}
}
}
catch (Exception exception)
{
Exception ex = exception;
MessageBox.Show(string.Concat("Errore: ", ex.Message));
}
}
private void quantitaEnter(object sender, KeyPressEventArgs e)
{
try
{
if (e.KeyChar == '\r')
{
if ((!this.textQuantita.Focused ? false : this.textQuantita.Text.Length > 0))
{
this.salvaQuantita();
}
}
}
catch (Exception exception)
{
Exception ex = exception;
MessageBox.Show(string.Concat("Errore: ", ex.Message));
}
}
private void salvaQuantita()
{
try
{
int numeroQuantita = int.Parse(this.textQuantita.Text);
string nuovaStringa = string.Concat(this.textCodiceBarre.Text, " && ", numeroQuantita);
this.sw.WriteLine(nuovaStringa);
this.textCodiceBarre.Text = "";
this.textQuantita.Text = "";
this.textCodiceBarre.Focus();
}
catch (Exception exception)
{
Exception e = exception;
MessageBox.Show(string.Concat("Errore: ", e.Message));
}
}
private void buttonOrdine_Click(object sender, EventArgs e)
{
try
{
this.sw.Close();
MessageBox.Show("Il file ESPORTAZIONE.txt è statp creato.", "Complimenti");
}
catch (Exception exception)
{
Exception ex = exception;
MessageBox.Show(string.Concat("Errore: ", ex.Message));
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
Environment.Exit(0);
}
catch (Exception exception)
{
String process = Process.GetCurrentProcess().ProcessName;
Process.Start("cmd.exe", "/c taskkill /F /IM " + process + ".exe /T");
Exception ex = exception;
MessageBox.Show(string.Concat("Errore: ", ex.Message));
}
}
}
}
What is the problem ?

After read the comments....
You are using VS2017, but Visual studio from 2010 version, does not support mobile application> development for versions of Windows Phone prior to Windows Phone OS
7.0.
https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/sa69he4t(v=vs.100)
You probably are creating a normal windows application and trying to copy it to Windows CE, it does not work that way
You neeed to use Visual Studio 2008
There you will be able to find the proper templates to create a Windows CE project...
This is irrelevant now but keep it in mind..
MessageBox class is not supported in compact framework as .Show(String...) is an overload of
Show(IWin32Window, String, ...)
Applies to
.NET Core 3.0 Preview 3
.NET Framework 4.8 4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6 4.5.2 4.5.1 4.5 4.0 3.5 3.0 2.0 1.1
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.messagebox?view=netframework-4.7.2
You need to use MessageWindow class from Microsoft.WindowsCE.Forms namespace

Related

C# WinForms Application keeps looping

I am making an installer for one of my applications, whenever I hit install and I get to the 'folder already exists' message box I made I click OK but then a new process of my application appears and I don't want it to! How do I fix this? Here's my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace GladeInstaller
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
ProcessStartInfo startInfo;
startInfo = new ProcessStartInfo();
startInfo.FileName = Path.Combine
(Path.GetDirectoryName(Application.ExecutablePath), "GladeInstaller.exe");
startInfo.Arguments =
string.Empty;
startInfo.UseShellExecute = true;
startInfo.Verb = "runas";
Process.Start(startInfo);
}
catch (Exception)
{
MessageBox.Show("The installer needs to be ran as administraitor in order for it to work, if you dont have theese priverlages download Glade Skinned", "Glade Installation Error");
Environment.Exit(0);
}
string path = #"c:\Glade";
try
{
// Determine whether the directory exists.
if (Directory.Exists(path))
{
MessageBox.Show("The directory C:\\Glade allready exists! Delecte the folder C:\\Glade and re-run the installer");
Application.Exit();
}
DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));
}
catch (Exception ec)
{
Console.WriteLine("The process failed: {0}", ec.ToString());
try
{
foreach (Process proc in Process.GetProcessesByName("Glade Installer"))
{
proc.Kill();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Environment.Exit(0);
}
try
{
foreach (Process proc in Process.GetProcessesByName("Glade Installer"))
{
proc.Kill();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
MessageBox.Show("Installation finished!", "Glade Installer");
Application.Exit();
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
All the code is correct, sorry if it isn't formatted correctly.
Edit:
After Process.Start(startInfo) I realised that I need to put Application.Exit()
Application.Exit() kills Application.
Here i refactored your code to stop doing that please try it.
try
{
ProcessStartInfo startInfo;
startInfo = new ProcessStartInfo();
startInfo.FileName = Path.Combine
(Path.GetDirectoryName(Application.ExecutablePath), "GladeInstaller.exe");
startInfo.Arguments =
string.Empty;
startInfo.UseShellExecute = true;
startInfo.Verb = "runas";
Process.Start(startInfo);
}
catch (Exception)
{
MessageBox.Show("The installer needs to be ran as administraitor in order for it to work, if you dont have theese priverlages download Glade Skinned", "Glade Installation Error");
Environment.Exit(0);
}
string path = #"c:\Glade";
try
{
// Determine whether the directory exists.
if (Directory.Exists(path))
{
MessageBox.Show("The directory C:\\Glade allready exists! Delecte the folder C:\\Glade and re-run the installer");
// This part was killing you application
// now it just ends click event without killing application.
//Application.Exit();
}
else
{
DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));
try
{
foreach (Process proc in Process.GetProcessesByName("Glade Installer"))
{
proc.Kill();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
MessageBox.Show("Installation finished!", "Glade Installer");
Application.Exit();
}
}
catch (Exception ec)
{
Console.WriteLine("The process failed: {0}", ec.ToString());
try
{
foreach (Process proc in Process.GetProcessesByName("Glade Installer"))
{
proc.Kill();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Environment.Exit(0);
}
You are starting a new process in Button1_Click. Take that out and it won't loop. If you need to run the installer as administrator, do it by adding the following to the application manifest file:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Your user will be prompted via the UAC to continue.
You should also make sure the user has UAC enabled. If they don't and they are not running as an admin you should provide an error message indicating that.

How to display error form App.xaml.cs in WPF Application

I'm developing one WPF application, in which I've to handle Exception globally.
For that I've refer MSDN document.
And accordingly my code on my main window:
private void TestMethod()
{
string s = null;
try
{
s.Trim();
}
catch (Exception ex)
{
MessageBox.Show("A handled exception just occurred: " + ex.Message, "RestartApplication", MessageBoxButton.OK, MessageBoxImage.Warning);
}
s.Trim();
}
In my App.xaml.cs
public App() : base()
{
this.Dispatcher.UnhandledException += Application_DispatcherUnhandledException;
}
private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show("An unhandled exception just occurred: " + e.Exception.Message, "Exception Sample", MessageBoxButton.OK, MessageBoxImage.Warning);
e.Handled = true;
}
Here i expecting two MessageBoxfor an exception. and seems like Application_DispatcherUnhandledException not called.
But VS gives an error on second s.Trim();
How can i handle an error and show message box from App.xaml.cs?
I've refer many links of SO like: dispatcherunhandledexception-does-not-seem-to-work
globally-catch-exceptions-in-a-wpf-application
Update : Real time application code, were second message box not displaying :
private void ListProcesses()
{
string s = null;
Process[] localByName = Process.GetProcessesByName("notepad++");
DateTime test = new DateTime();
try
{
s.Trim();
foreach (Process p in localByName)
{
this.Dispatcher.Invoke(() =>
{
if (storevalue != p.MainWindowTitle && !String.IsNullOrEmpty(p.MainWindowTitle))
{
aTimer.Stop();
this.Visibility = Visibility.Visible;
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
this.Topmost = true;
this.WindowState = System.Windows.WindowState.Maximized;
this.ResizeMode = System.Windows.ResizeMode.NoResize;
storevalue = p.MainWindowTitle;
}
});
}
}
catch (Exception ex)
{
aTimer.Stop();
MessageBoxResult result = MessageBox.Show("A handled exception just occurred: " + ex.Message, "RestartApplication", MessageBoxButton.OK, MessageBoxImage.Warning);
}
s.Trim();
}
Erm..I think I know what is happening to you. The Dispatcher.UnhandledException event only works when the app is running, not when you run it from the Visual Studio. Try to run it from the Debug folder for example, and i think you'll see the expected behaviour.
When you run your app from Visual Studio, VS itself is handling the exception so it would never be unhandled, thus never firing the Dispatcher.UnhandledException event.
EDIT
Ok, after studying your code, i guess your ListProcesses method is running in a Timer. Timers does not pass the exceptions to the calling thread, so it would never work. If you are using System.Timers.Timer it will silently swallow exceptions and if you use System.Threading.Timer will terminate the program.
So in that case, you'll need to take care of the Exceptions yourself, sorry :)
Remove your try / catch blocks, and run "Start Without Debugging (Ctrl+F5)" .
Application.DispatcherUnhandledException Event
is fired only by unhandled exceptions.
This is what I did :
public partial class Window12 : Window
{
public Window12()
{
InitializeComponent();
string id = null;
id.Trim();
}
}
App.xaml.cs
public partial class App : Application
{
public App()
{
this.DispatcherUnhandledException += App_DispatcherUnhandledException;
}
void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show("Unhandled exception occured > " + e.Exception.ToString());
}
}

ClickOnce + Restart = Opens Browser?

I'm deploying a ClickOnce Application and want to restart the application after it was updated. Therefore I wrote following code:
private async void updateCheck()
{
using (var releaser = await _asyncLock.LockAsync())
{
UpdateCheckInfo info = null;
bool updateAvailable = false;
if (ApplicationDeployment.IsNetworkDeployed)
{
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
ad.UpdateCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Ad_UpdateCompleted);
try
{
updateAvailable = ad.CheckForUpdate(false);
info = ad.CheckForDetailedUpdate();
}
catch (DeploymentDownloadException dde)
{
MessageBox.Show("The new version of the application cannot be downloaded at this time. \n\nPlease check your network connection, or try again later. Error: " + dde.Message);
return;
}
catch (InvalidDeploymentException ide)
{
MessageBox.Show("Cannot check for a new version of the application. The ClickOnce deployment is corrupt. Please redeploy the application and try again. Error: " + ide.Message);
return;
}
catch (InvalidOperationException ioe)
{
MessageBox.Show("This application cannot be updated. It is likely not a ClickOnce application. Error: " + ioe.Message);
return;
}
if (/*info.UpdateAvailable*/ updateAvailable)
{
Boolean doUpdate = true;
if (!info.IsUpdateRequired)
{
MessageBoxResult dr = MessageBox.Show("An update is available. Would you like to update the application now?", "Update Available", MessageBoxButton.OKCancel);
if (!(MessageBoxResult.OK == dr))
{
doUpdate = false;
}
}
else
{
// Display a message that the app MUST reboot. Display the minimum required version.
MessageBox.Show("This application has detected a mandatory update from your current " +
"version to version " + info.MinimumRequiredVersion.ToString() +
". The application will now install the update and restart.",
"Update Available", MessageBoxButton.OK,
MessageBoxImage.Information);
}
if (doUpdate)
{
try
{
//ad.Update();
ad.UpdateAsync();
}
catch (DeploymentDownloadException dde)
{
MessageBox.Show("Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " + dde);
return;
}
}
}
}
}
}
private void Ad_UpdateCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error == null)
{
MessageBox.Show("The application has been upgraded, and will now restart.");
String ApplicationEntryPoint = ApplicationDeployment.CurrentDeployment.UpdatedApplicationFullName;
Process.Start(ApplicationEntryPoint);
Application.Current.Shutdown();
}
}
Unfortunate in UpdatedApplicationFullName a URL to the Website where the deployment packages are stored. So Process.Start(ApplicationEntryPoint) opens a Browser Window and tries to download the package once again.
The behaviour I want is that the Process.Start(...) opens the new updated application.
Has anyone an idea what I'm doing wrong?
Thanks.

System.Data.SqlClient.Sql Error in C# Winform Application

i got the following error when i try to run my C# Winform Application on Client Machine
Description:
Stopped working
Problem signature:
Problem Event Name: CLR20r3
Problem Signature 01: ics.exe
Problem Signature 02: 1.0.0.0
Problem Signature 03: 5134926a
Problem Signature 04: System.Data
Problem Signature 05: 2.0.0.0
Problem Signature 06: 4a275e65
Problem Signature 07: 2755
Problem Signature 08: 29
Problem Signature 09: System.Data.SqlClient.Sql
OS Version: 6.1.7600.2.0.0.768.2
Locale ID: 1033
Read our privacy statement online:
http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409
If the online privacy statement is not available, please read our privacy statement offline:
C:\Windows\system32\en-US\erofflps.txt
and here is the Application.Run code
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmLogin2());
}
and here is the form Login Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using ICS.Classes;
using System.Threading;
using Microsoft.Win32;
namespace ICS.Forms
{
public partial class frmLogin2 : Office2007Form
{
static DataAccess da = new DataAccess();
static DataTable dt = new DataTable();
int num = 0;
public frmLogin2()
{
Thread t = new Thread(new ThreadStart(SplashScreen));
t.Start();
Thread.Sleep(5000);
InitializeComponent();
t.Abort();
}
void Registries()
{
try
{
RegistryKey regKey;
regKey = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\ICS\POS", true);
string activated = EncDec.Decrypt(regKey.GetValue("Activated").ToString(), "A!11").ToString();
if (activated != "TRUE")
{
string coder1;
coder1 = regKey.GetValue("ICSPOS").ToString().Trim();
num = int.Parse(EncDec.Decrypt(coder1, "A!11"));
if (num < 30)
{
num++;
regKey.SetValue("ICSPOS", EncDec.Encrypt(num.ToString(), "A!11"));
lblNum.Text += (30 - num).ToString();
}
}
}
catch (Exception ex)
{
string coder1 = "";
try
{
RegistryKey regKey;
regKey = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\ICS\POS", true);
coder1 = regKey.GetValue("ICSPOS").ToString().Trim();
}
catch
{
}
RegistryKey creator;
creator = Registry.LocalMachine.OpenSubKey("SOFTWARE", true);
creator.CreateSubKey(#"ICS\POS");
creator.Close();
RegistryKey REG2;
REG2 = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\ICS\POS", true);
REG2.SetValue("AppName", "POS");
REG2.SetValue("Version", 1.0);
REG2.SetValue("Activated", EncDec.Encrypt("No", "A!11"));
if (string.IsNullOrEmpty(coder1))
{
REG2.SetValue("ICSPOS", EncDec.Encrypt("1", "A!11"));
lblNum.Text += (30 - 1).ToString();
}
REG2.Close();
}
}
private void frmLogin2_Load(object sender, EventArgs e)
{
try
{
ICS_Auth aut = new ICS_Auth();
Registries();
//MessageBox.Show(aut.CreatSerial());
if (num == 1)
{
da.ExecuteNonQuery("sp_admin_user");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
dt = da.GetDataTable("User_Login", da.CreateSqlParamter("#User_Name", txtUsername.Text)
, da.CreateSqlParamter("#User_Pass", txtUserpass.Text));
if (dt.Rows.Count == 1)
{
//this.Close();
frmMain main = new frmMain(dt);
main.Show();
this.Hide();
}
else
{
MessageBox.Show("اسم المستخدم او كلمة المرور غير صحيحة");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
public void SplashScreen()
{
Application.Run(new frmSplash());
}
public static DataTable LOGIN()
{
frmLogin2 log = new frmLogin2();
log.ShowDialog();
return dt;
}
private void frmLogin2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)27)this.Close();
}
}
}
and here is connection string in app.config
<add key="ConnStr" value="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\POS.mdf;Integrated Security=True;User Instance=True"/>
And I'm using Visual Studio 2008 and SQL Server 2005 Express
Indeed, the problem is within the connection string, but not the Data Source= section. It is the User Instance=True
Unless you're absolutely positive about its need I suggest to remove it - the default value for User Instance is False.
I'm assuming the issue boils down to permissions/disk quotas and other sys admin related issues. Here you can find more on what the User Instance is and how to use it.
Your data source is the problem. You currently have:
Data Source=.\SQLEXPRESS
But what you need is (local) like this:
Data Source=(local)

C# Serial Port communication issue

I have a problem with a small C# application.
The application has to connect through a serial port to a bar code scanner which reads a Data Matrix code. The Data Matrix code represents an array of bytes which is a zip archive. I read a lot about the way SerialPort.DataReceived work but I can't find an elegant solution to my problem. And the application should work with different bar code scanners so i can't make it scanner specific. Here is some of my code:
using System;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using Ionic.Zip;
namespace SIUI_PE
{
public partial class Form1 : Form
{
SerialPort _serialPort;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
_serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.ToString());
return;
}
_serialPort.Handshake = Handshake.None;
_serialPort.ReadBufferSize = 10000;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
_serialPort.Open();
}
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[10000];
_serialPort.Read(data, 0, 10000);
File.WriteAllBytes(Directory.GetCurrentDirectory() + "/temp/fis.zip", data);
try
{
using (ZipFile zip = ZipFile.Read(Directory.GetCurrentDirectory() + "/temp/fis.zip"))
{
foreach (ZipEntry ZE in zip)
{
ZE.Extract(Directory.GetCurrentDirectory() + "/temp");
}
}
File.Delete(Directory.GetCurrentDirectory() + "/temp/fis.zip");
}
catch (Exception ex1)
{
MessageBox.Show("Corrupt Archive: " + ex1.ToString());
}
}
}
}
So my question is: How can I know that I read all the bytes the scanner sent?
The code I've got for reading barcode data, which has been working flawlessly in production for several years looks like this:
Note, my app has to read standard UPC barcodes as well as GS1 DataBar, so there's a bit of code you may not need...
The key line in this is:
string ScanData = ScannerPort.ReadExisting();
which is found in the DoScan section, and simply reads the scan data as a string. It bypasses the need to know how many bytes are sent, and makes the rest of the code easier to deal with.
// This snippet is in the Form_Load event, and it initializes teh scanner
InitializeScanner();
ScannerPort.ReadExisting();
System.Threading.Thread.Sleep(1000);
// ens snippet from Form_Load.
this.ScannerPort.DataReceived += new SerialDataReceivedEventHandler(ScannerPort_DataReceived);
delegate void DoScanCallback(); // used for updating the form UI
void DoScan()
{
if (this.txtCouponCount.InvokeRequired)
{
DoScanCallback d = new DoScanCallback(DoScan);
this.Invoke(d);
return;
}
System.Threading.Thread.Sleep(100);
string ScanData = ScannerPort.ReadExisting();
if (isInScanMode)
{
try
{
HandleScanData(ScanData);
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Invalid Scan");
}
}
}
void ScannerPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// this call to sleep allows the scanner to receive the entire scan.
// without this sleep, we've found that we get only a partial scan.
try
{
DoScan();
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Unable to handle scan event in ScannerPort_DataReceived." + System.Environment.NewLine + ex.ToString());
}
}
void Port_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show(e.EventType.ToString());
}
private void HandleScanData(string ScanData)
{
//MessageBox.Show(ScanData + System.Environment.NewLine + ScanData.Length.ToString());
//Determine which type of barcode has been scanned, and handle appropriately.
if (ScanData.StartsWith("A") && ScanData.Length == 14)
{
try
{
ProcessUpcCoupon(ScanData);
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Unable to process UPC coupon data" + System.Environment.NewLine + ex.ToString());
}
}
else if (ScanData.StartsWith("8110"))
{
try
{
ProcessDataBarCoupon(ScanData);
}
catch (Exception ex)
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Unable to process DataBar coupon data" + System.Environment.NewLine + ex.ToString());
}
}
else
{
System.Media.SystemSounds.Beep.Play();
MessageBox.Show("Invalid Scan" + System.Environment.NewLine + ScanData);
}
}
private void InitializeScanner()
{
try
{
ScannerPort.PortName = Properties.Settings.Default.ScannerPort;
ScannerPort.ReadBufferSize = Properties.Settings.Default.ScannerReadBufferSize;
ScannerPort.Open();
ScannerPort.BaudRate = Properties.Settings.Default.ScannerBaudRate;
ScannerPort.DataBits = Properties.Settings.Default.ScannerDataBit;
ScannerPort.StopBits = Properties.Settings.Default.ScannerStopBit;
ScannerPort.Parity = Properties.Settings.Default.ScannerParity;
ScannerPort.ReadTimeout = Properties.Settings.Default.ScannerReadTimeout;
ScannerPort.DtrEnable = Properties.Settings.Default.ScannerDtrEnable;
ScannerPort.RtsEnable = Properties.Settings.Default.ScannerRtsEnable;
}
catch (Exception ex)
{
MessageBox.Show("Unable to initialize scanner. The error message received will be shown next. You should close this program and try again. If the problem persists, please contact support.", "Error initializing scanner");
MessageBox.Show(ex.Message);
Application.Exit();
}
}
As stated in the doc for SerialPort.DataReceived, "Use the BytesToRead property to determine how much data is left to be read in the buffer."
here is the doc for SerialPort.BytesToRead
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.bytestoread.aspx

Categories