I've made a Windows Form using C# and I'm trying to read serial DATA from RS232 serial port. But when I try to connect the device with PC through serial port. Device connected successfully but nothing is being received on the serial port through RS232.
Here is the main 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.IO.Ports;
using WindowsFormsApp1;
using System.Data.SQLite;
using System.Windows.Forms.DataVisualization.Charting;
namespace Weight_Scale
{
public partial class FormWeightScale : Form
{
string weight;
string dbFile = "BundleInstances.db";
bundle bundle1 = new bundle();
int h = 0 , m = 0, s = 0 ;
public FormWeightScale()
{
InitializeComponent();
PageWeightScale();
if (!File.Exists(dbFile))
{
SQLiteConnection.CreateFile(dbFile);
}
//----------------- Queries ----------------------//
string createTable = "CREATE TABLE IF NOT EXISTS bundle" +
"(ID integer PrimaryKey AutoIncreament Unique Not Null," +
"Date VARCHAR, Time VARCHAR, Size VARCHAR, BarGrade VARCHAR," +
"Length VARCHAR, HeatNumber VARCHAR, WeightZeroLevel VARCHAR," +
"WeightReadingLevel VARCHAR, BundleMaxWeight VARCHAR, Weight integer)";
bundle1.setQueryCreateTable(createTable);
bundle.createTable();
setData();
displayData();
var ports = SerialPort.GetPortNames();
ComboBoxPort.DataSource= ports;
ProgressBarConnection.Value = 0;
}
void setData()
{
bundle1.setDateQuery(DateTimePickerWeight.Value.ToString("dd-MM-yyyy"));
}
void displayData()
{
dataGridWeightInstances.DataSource = bundle.readTable();
chartWeight.DataSource = bundle.readTable();
chartWeight.Series["Weight"].Points.Clear();
chartWeight.Series["Weight"].XValueMember = "Date";
chartWeight.Series["Weight"].XValueMember = "Time";
chartWeight.Series["Weight"].YValueMembers = "Weight";
labelPerDayProduction.Text = bundle.totalPerDayProduction.ToString("000.0");
}
private void BtnConnect_Click(object sender, EventArgs e)
{
if (ComboBoxPort.SelectedIndex > -1)
{
if(BtnConnect.Text == "Connect")
{
MessageBox.Show(String.Format("You selected port '{0}'", ComboBoxPort.SelectedItem), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Connection(ComboBoxPort.SelectedItem.ToString());
}
else
{
MessageBox.Show("Please select a port first");
}
}
private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
{
serialPort1.Close();
ProgressBarConnection.Value=0;
Application.Exit();
}
private void ConfigurationToolStripMenuItem_Click(object sender, EventArgs e)
{
PageConfiguration();
}
private void WeightScaleToolStripMenuItem_Click(object sender, EventArgs e)
{
PageWeightScale();
}
private void ComboBoxPort_TextChanged(object sender, EventArgs e)
{
string[] sport = SerialPort.GetPortNames();
toolStripComboBoxPort.Items.AddRange(sport);
}
private void FormWeightScale_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
}
}
//--------------------------- Function for Connecting to Serial Port ----------------------------//
private void Connection(string portName)
{
if (BtnConnect.Text == "Connect")
{
try
{
serialPort1.PortName = portName;
serialPort1.BaudRate = Convert.ToInt32(comboBoxBaudRate.Text);
serialPort1.DataBits = Convert.ToInt32(comboBoxDataBits.Text);
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), comboBoxParity.Text);
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBoxStopBits.Text);
//serialPort1.RtsEnable= true;
//serialPort1.DtrEnable= true;
serialPort1.Open();
Console.WriteLine("Connection is open");
ProgressBarConnection.Value = 100;
BtnConnect.Text = "Disconnect";
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
serialPort1.Close();
BtnConnect.Text = "Connect";
ProgressBarConnection.Value = 0;
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
weight = serialPort1.ReadLine();
this.Invoke(new EventHandler(ShowData));
if(int.Parse(weight.ToString()) >= int.Parse(textBoxReadingLevel.Text))
{
this.Invoke(new EventHandler(setBundleData));
string insertQuery = "INSERT INTO bundle (ID , Date , Time , Size , BarGrade," +
"Length , HeatNumber , WeightZeroLevel , WeightReadingLevel ," +
"BundleMaxWeight , Weight )" +
"VALUES (#ID , #date ,#time , #barSize , #barGrade , #bundleLength , #bundleHeatNumber ," +
"#bundleWeightZeroLevel , #bundleWeightReadingLevel , #bundleMaxWeight , #bundleWeight)";
bundle1.setQueryInsertRow(insertQuery);
bundle.insertRow();
this.Invoke(new EventHandler(displayDataOnGridChart));
}
}
private void displayDataOnGridChart(object sender, EventArgs e)
{
labelPerDayProduction.Text = bundle.totalPerDayProduction.ToString("000.0");
dataGridWeightInstances.DataSource = bundle.readTable();
chartWeight.DataSource = bundle.readTable();
chartWeight.Series["Weight"].Points.Clear();
chartWeight.Series["Weight"].XValueMember = "Date";
chartWeight.Series["Weight"].XValueMember = "Time";
chartWeight.Series["Weight"].YValueMembers = "Weight";
}
private void setBundleData(object sender, EventArgs e)
{
DateTime dt = DateTime.Now;
bundle1.setDateQuery(DateTimePickerWeight.Value.ToString("dd-MM-yyyy"));
bundle1.setDate(dt.ToString("dd-MM-yyyy"));
bundle1.setTime(dt.ToString("HH:mm-tt"));
bundle1.setBarSize(ComboBoxBarSize.SelectedItem.ToString());
bundle1.setBarGrade(ComboBoxBarGrade.SelectedItem.ToString());
bundle1.setBundleLength(TextBoxCutLength.Text);
bundle1.setBundleHeatNumber(textBoxHeatNumber.Text);
bundle1.setBundleWeightZeroLevel(textBoxZeroLevel.Text);
bundle1.setBundleWeightReadingLevel(textBoxReadingLevel.Text);
bundle1.setBundleMaxWeight(textBoxMaxWeight.Text);
bundle1.setBundleWeight(int.Parse(weight.ToString()));
}
private void ShowData(object sender, EventArgs e)
{
TimerWeight.Stop();
h = 0; m = 0; s = 0;
LabelWeight.Text = weight.ToString();
TimerWeight.Interval = 1000;
TimerWeight.Start();
}
private void ComboBoxBarSize_MouseEnter(object sender, EventArgs e)
{
//ComboBoxBarSize.Text = "";
}
private void ComboBoxBarSize_MouseClick(object sender, MouseEventArgs e)
{
ComboBoxBarSize.Text = "";
}
private void ComboBoxBarSize_MouseLeave(object sender, EventArgs e)
{
ComboBoxBarSize.Text = "Bar Size";
}
private void ComboBoxPort_MouseHover(object sender, EventArgs e)
{
string[] sport = SerialPort.GetPortNames();
toolStripComboBoxPort.Items.AddRange(sport);
}
//------------------------ Functions for PAGES -------------------------//
private void PageConfiguration()
{
DateTimePickerWeight.Hide();
labelBarSize.Hide();
labelBarGrade.Hide();
labelBarCutLength.Hide();
labelHeatNumber.Hide();
labelZeroLevel.Hide();
labelReadingLevel.Hide();
labelMaxWeight.Hide();
LabelWeight.Hide();
labelStableWeightCounter.Hide();
labelPerDayProduction.Hide();
ComboBoxBarSize.Hide();
ComboBoxBarGrade.Hide();
TextBoxCutLength.Hide();
textBoxHeatNumber.Hide();
textBoxZeroLevel.Hide();
textBoxReadingLevel.Hide();
textBoxMaxWeight.Hide();
checkBoxBarSize.Hide();
checkBoxBarGrade.Hide();
checkBoxBarCutLength.Hide();
checkBoxHeatNumber.Hide();
comboBoxChartType.Hide();
chartWeight.Hide();
dataGridWeightInstances.Hide();
labelPort.Show();
labelBaudRate.Show();
labelParity.Show();
labelDataBits.Show();
labelStopBits.Show();
ComboBoxPort.Show();
comboBoxBaudRate.Show();
comboBoxParity.Show();
comboBoxDataBits.Show();
comboBoxStopBits.Show();
BtnConnect.Show();
}
private void PageWeightScale()
{
DateTimePickerWeight.Show();
labelBarSize.Show();
labelBarGrade.Show();
labelBarCutLength.Show();
labelHeatNumber.Show();
labelZeroLevel.Show();
labelReadingLevel.Show();
labelMaxWeight.Show();
LabelWeight.Show();
labelStableWeightCounter.Show();
labelPerDayProduction.Show();
ComboBoxBarSize.Show();
ComboBoxBarGrade.Show();
TextBoxCutLength.Show();
textBoxHeatNumber.Show();
textBoxZeroLevel.Show();
textBoxReadingLevel.Show();
textBoxMaxWeight.Show();
checkBoxBarSize.Show();
checkBoxBarGrade.Show();
checkBoxBarCutLength.Show();
checkBoxHeatNumber.Show();
comboBoxChartType.Show();
chartWeight.Show();
dataGridWeightInstances.Show();
labelPort.Hide();
labelBaudRate.Hide();
labelParity.Hide();
labelDataBits.Hide();
labelStopBits.Hide();
ComboBoxPort.Hide();
comboBoxBaudRate.Hide();
comboBoxParity.Hide();
comboBoxDataBits.Hide();
comboBoxStopBits.Hide();
BtnConnect.Hide();
if (ComboBoxBarSize.Text == "")
{
ComboBoxBarSize.Text = "Bar Size";
}
if (ComboBoxBarGrade.Text == "")
{
ComboBoxBarGrade.Text = "Bar Grade";
}
}
private void DateTimePickerWeight_ValueChanged(object sender, EventArgs e)
{
setData();
displayData();
}
private void DateTimePickerWeight_MouseDown(object sender, MouseEventArgs e)
{
setData();
displayData();
}
private void comboBoxChartType_SelectedValueChanged(object sender, EventArgs e)
{
chartWeight.Series["Weight"].ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), comboBoxChartType.Text);
}
private void TimerWeight_Tick(object sender, EventArgs e)
{
if (int.Parse(weight.ToString()) >= int.Parse(textBoxReadingLevel.Text))
{
s += 1;
if (s == 60)
{
s = 0;
m += 1;
if (m == 60)
{
h += 1;
}
}
labelStableWeightCounter.Text = string.Format("{0}:{1}:{2}", h.ToString().PadLeft(2, '0'), m.ToString().PadLeft(2, '0'), s.ToString().PadLeft(2, '0'));
}
}
}
}
Here is the Class of bundles
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.Data;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
internal class bundle
{
// ------------------------- Variables for DATABASE DATA ---------------------//
public static int bundleID;
public static string date;
public static string time;
public static string barSize;
public static string barGrade;
public static string bundleLength;
public static string bundleHeatNumber;
public static string bundleWeightZeroLevel;
public static string bundleWeightReadingLevel;
public static string bundleMaxWeight;
public static int bundleWeight;
// ------------------------- Variables for Queries ---------------------//
public static double totalPerDayProduction;
public static string dateQuery;
public static string dbFile = "Data Source = BundleInstances.db; Version = 3";
public static string queryCreateTable;
public static string queryInsertRow;
public static string queryReadDataGrid;
public static SQLiteDataReader reader;
//---------------- Constructor ----------------//
public bundle() { }
//---------------- Set the Variable of the Class ----------------//
public string setDate(string dt)
{
date = dt;
return date;
}
public string setTime(string t)
{
time = t;
return time;
}
public int setbundleID(int bID)
{
bundleID = bID;
return bundleID;
}
public string setBarSize(string bSize)
{
barSize = bSize;
return barSize;
}
public string setBarGrade(string bGrade)
{
barGrade = bGrade;
return barGrade;
}
public string setBundleLength(string bLength)
{
bundleLength = bLength;
return bundleLength;
}
public string setBundleHeatNumber(string bHeatNumber)
{
bundleHeatNumber = bHeatNumber;
return bundleHeatNumber;
}
public string setBundleWeightZeroLevel(string bWeightZeroLevel)
{
bundleWeightZeroLevel = bWeightZeroLevel;
return bundleWeightZeroLevel;
}
public string setBundleWeightReadingLevel(string bWeightReadingLevel)
{
bundleWeightReadingLevel = bWeightReadingLevel;
return bundleWeightReadingLevel;
}
public string setBundleMaxWeight(string bMaxWeight)
{
bundleMaxWeight = bMaxWeight;
return bundleMaxWeight;
}
public int setBundleWeight(int bWeight)
{
bundleWeight = bWeight;
return bundleWeight;
}
public string setDateQuery(string dt)
{
dateQuery = dt;
return dateQuery;
}
//---------------- Set Query strings of Class ----------------//
public string setQueryCreateTable(string qCreateTable)
{
queryCreateTable = qCreateTable;
return queryCreateTable;
}
public string setQueryInsertRow(string qInsertRow)
{
queryInsertRow = qInsertRow;
return queryInsertRow;
}
public string setQueryReadDataGrid(string qReadDataGrid)
{
queryReadDataGrid = qReadDataGrid;
return queryReadDataGrid;
}
//---------------- Queries Section ----------------//
//---------------- Create Table ----------------//
public static void createTable()
{
SQLiteConnection dbConnection = new SQLiteConnection(dbFile);
dbConnection.Open();
SQLiteCommand command = new SQLiteCommand(queryCreateTable, dbConnection);
command.ExecuteNonQuery();
dbConnection.Close();
}
//---------------- Insert Record ----------------//
public static void insertRow()
{
SQLiteConnection dbConnection = new SQLiteConnection(dbFile);
dbConnection.Open();
SQLiteCommand getIDcmd = new SQLiteCommand("SELECT MAX(ID) FROM bundle", dbConnection);
object maxID = getIDcmd.ExecuteScalar();
if (maxID.ToString() == "")
{
bundleID = 1;
}
else
{
bundleID = int.Parse(maxID.ToString());
bundleID++;
}
SQLiteCommand command = new SQLiteCommand(queryInsertRow, dbConnection);
command.Parameters.AddWithValue("#ID", bundleID++);
command.Parameters.AddWithValue("#date", date);
command.Parameters.AddWithValue("#time", time);
command.Parameters.AddWithValue("#barSize", barSize);
command.Parameters.AddWithValue("#barGrade", barGrade);
command.Parameters.AddWithValue("#bundleLength", bundleLength);
command.Parameters.AddWithValue("#bundleHeatNumber", bundleHeatNumber);
command.Parameters.AddWithValue("#bundleWeightZeroLevel", bundleWeightZeroLevel);
command.Parameters.AddWithValue("#bundleWeightReadingLevel", bundleWeightReadingLevel);
command.Parameters.AddWithValue("#bundleMaxWeight", bundleMaxWeight);
command.Parameters.AddWithValue("#bundleWeight", bundleWeight);
command.ExecuteNonQuery();
dbConnection.Close();
}
//---------------- Data Reader ----------------//
public static DataTable readTable()
{
DataTable dt = new DataTable();
string dbFile = "Data Source = BundleInstances.db; Version = 3";
SQLiteConnection dbConnection = new SQLiteConnection(dbFile);
dbConnection.Open();
SQLiteCommand getMaxWeightcmd = new SQLiteCommand("SELECT SUM(Weight) FROM bundle WHERE Date = #dateQuery", dbConnection);
getMaxWeightcmd.Parameters.AddWithValue("#dateQuery", dateQuery);
object weightSum = getMaxWeightcmd.ExecuteScalar();
if(weightSum.ToString() != "")
{
totalPerDayProduction = Convert.ToDouble(weightSum.ToString()) / 1000;
}
else
{
totalPerDayProduction = 0;
}
string readTable = "SELECT Date , Time , Size , Length, Weight FROM bundle WHERE Date = #dateQuery ORDER BY ID DESC";
SQLiteCommand command = new SQLiteCommand(readTable, dbConnection);
command.Parameters.AddWithValue("#dateQuery", dateQuery);
reader = command.ExecuteReader();
dt.Load(reader);
dbConnection.Close();
return dt;
}
}
}
Here is the picture of Form1.cs[Design]
Form1.cs[Design]
Here is Configuration Page:
Configuration
Weight Scale Page is:
Weight Scale
Picture of Connection of RS232 PC Side:
PC Side DB9 Connector
Picture of Connection of RS232 Device Side:
Device Side Connector Connection
The received value should be displayed on the LABEL. At present, 2080 is the TEXT Value.
The port setting is displayed here:
I try this code with arduino MEGA2560. This winform is receiving DATA serially when connected with Arduino.
Related
I was following a tutorial to connect my bluetooth module to pc and read data from it, but in the tutorial he designed the program to run as a GUI, now I'm trying to edit it to run in console, which I will merge the new code in unity engine to move my game by the input data.
The GUI
used and the 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.Threading;
using InTheHand;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using System.IO;
namespace Bluetooth
{
public partial class Form1 : Form
{
List<string> items;
public Form1()
{
items = new List<string>();
InitializeComponent();
}
private void bGo_Click(object sender, EventArgs e)
{
if(serverStarted)
{
updateUI("Server already started!");
return;
}
if(rbClient.Checked)
{
connectAsClient();
}
else
{
connectAsServer();
}
}
private void connectAsServer()
{
Thread bluetoothServerThread = new Thread(new ThreadStart(serverConnectThread));
bluetoothServerThread.Start();
}
Guid mUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
bool serverStarted = false;
public void serverConnectThread()
{
serverStarted = true;
updateUI("Server started, waiting for clients");
BluetoothListener blueListener = new BluetoothListener(mUUID);
blueListener.Start();
BluetoothClient conn = blueListener.AcceptBluetoothClient();
updateUI("Client has connected");
Stream mstream = conn.GetStream();
while (true)
{
try
{
//handle server connection
byte[] received = new byte[1024];
mstream.Read(received, 0, received.Length);
updateUI("Received: " + Encoding.ASCII.GetString(received));
byte[] sent = Encoding.ASCII.GetBytes("Hello world\n");
mstream.Write(sent, 0, sent.Length);
}
catch (IOException exception)
{
updateUI("Client has disconnected!!");
break;
}
}
}
private void connectAsClient()
{
startScan();
}
private void startScan()
{
listBox1.DataSource = null;
listBox1.Items.Clear();
items.Clear();
Thread bluetoothScanThread = new Thread(new ThreadStart(scan));
bluetoothScanThread.Start();
}
BluetoothDeviceInfo[] devices;
private void scan()
{
updateUI("Start scanning...");
BluetoothClient client = new BluetoothClient();
devices = client.DiscoverDevicesInRange();
updateUI(devices.Length.ToString() + " devices discovered");
updateUI("Scan complete");
foreach(BluetoothDeviceInfo d in devices)
{
items.Add(d.DeviceName);
}
updateDeviceList();
}
private void updateUI(string message)
{
Func<int> del = delegate ()
{
tbOutput.AppendText(message + System.Environment.NewLine);
return 0;
};
Invoke(del);
}
private void updateDeviceList()
{
Func<int> del = delegate ()
{
listBox1.DataSource = items;
return 0;
};
Invoke(del);
}
BluetoothDeviceInfo DeviceInfo;
private void listBox1_DoubleClick(object sender, EventArgs e)
{
DeviceInfo = devices.ElementAt(listBox1.SelectedIndex);
updateUI(DeviceInfo.DeviceName + " was Selected, attempting connect");
if(PairDevice())
{
updateUI("Device paired");
updateUI("starting connect thread");
Thread bluetoothClientThread = new Thread(new ThreadStart(ClientConnectThread));
bluetoothClientThread.Start();
}
else
{
updateUI("pair failed");
}
}
private void ClientConnectThread()
{
BluetoothClient client = new BluetoothClient();
updateUI("Attempting connect");
client.BeginConnect(DeviceInfo.DeviceAddress, mUUID, this.BluetoothClientConnectCallback, client);
}
void BluetoothClientConnectCallback(IAsyncResult result)
{
BluetoothClient client = (BluetoothClient)result.AsyncState;
client.EndConnect(result);
Stream stream = client.GetStream();
stream.ReadTimeout = 10000;
while(true)
{
try
{
byte[] received = new byte[1024];
stream.Read(received, 0, received.Length);
updateUI(Encoding.ASCII.GetString(received));
}
catch (IOException exception)
{
updateUI("Client has disconnected!!");
break;
}
}
}
string mypin = "1234";
private bool PairDevice()
{
if(!DeviceInfo.Authenticated)
{
if (!BluetoothSecurity.PairRequest(DeviceInfo.DeviceAddress, mypin)) ;
{
return false;
}
}
return true;
}
bool ready = false;
byte[] message;
private void tbText_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == 13)
{
byte[] b = Encoding.ASCII.GetBytes(tbText.Text);
ready = true;
tbText.Clear();
}
}
}
}
I tried to edit my code but I don't know why scan method can't be called.
class Program
{
Guid mUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
List<string> items = new List<string>();
BluetoothDeviceInfo[] devices;
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Thread bluetoothScanThread = new Thread(new ThreadStart(scan));
bluetoothScanThread.Start();
}
public void scan()
{
Console.WriteLine("Start scanning...");
BluetoothClient client = new BluetoothClient();
devices = client.DiscoverDevicesInRange();
Console.WriteLine(devices.Length.ToString() + " devices discovered");
Console.WriteLine("Scan complete");
foreach (BluetoothDeviceInfo d in devices)
{
items.Add(d.DeviceName);
}
}
}
So, I have a win form where I have to search for a string in a text file and display the line number and the entire line if I found the string. The search has to be multithreaded and all the line numbers and the lines must be on a listview. For example if the word "language" is in line number 60 , the listview must display:
60 "the line has the word language"
I have used the background worker in this regard but I am not being able to display the correct line number and the lines. Firstly, one line is being displayed multiple times and secondly, the line number is always coming to be 0. However, when I output the result in Console, the result is correct. I think I am making some error in putting the result into the listview.
Here' s my main form.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// private bool start_cancel;
bool bln = true;
private void StartCancelbtn_Click(object sender, EventArgs e)
{
if (bln)
text2();
else
text1();
bln = !bln;
}
private void text1()
{
StartCancelbtn.Text = "Start";
this.backgroundWorker1.CancelAsync();
}
private void text2()
{
StartCancelbtn.Text = "Cancel";
StartThread();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
System.ComponentModel.BackgroundWorker worker;
worker = (System.ComponentModel.BackgroundWorker)sender;
// Get the Words object and call the main method.
main_work WC = (main_work)e.Argument;
WC.CountWords(worker, e);
if (worker.CancellationPending)
{
e.Cancel = true;
// break;
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
main_work.ReportState state =
(main_work.ReportState)e.UserState;
ListViewItem l1 = new ListViewItem();
l1.Text = state.LinesCounted.ToString();
l1.SubItems.Add(state.line);
listView1.Items.Add(l1);
}
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
MessageBox.Show("Error: " + e.Error.Message);
else if (e.Cancelled)
MessageBox.Show("Word counting canceled.");
else
MessageBox.Show("Finished counting words.");
}
private void StartThread()
{
main_work WC = new main_work();
WC.CompareString = this.searchtext.Text;
WC.SourceFile = this.filenametextbox.Text;
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync(WC);
}
private void browsebtn_Click(object sender, EventArgs e)
{
using (OpenFileDialog brw = new OpenFileDialog())
{
if (brw.ShowDialog() == DialogResult.OK)
{
using (StreamReader sr = new StreamReader(brw.FileName))
{
filenametextbox.Text = brw.FileName.ToString();
}
}
}
}
}
}
Here is my main_work class where the actual comparison is happening:
class main_work
{
public class ReportState
{
public int LinesCounted;
public string line;
}
Queue q = new Queue();
public string SourceFile;
public string CompareString;
public string line2 ;
public int linenumber=0;
public int linenumber1 = 0;
int LinesCounted1;
// public string line2;
public void CountWords(
System.ComponentModel.BackgroundWorker worker,
System.ComponentModel.DoWorkEventArgs e)
{
// Initialize the variables.
ReportState state = new ReportState();
string line1 = "";
int elapsedTime = 1;
DateTime lastReportDateTime = DateTime.Now;
if (CompareString == null ||
CompareString == System.String.Empty)
{
MessageBox.Show("Please Enter a string to be searched");
}
else
{
// Open a new stream.
using (System.IO.StreamReader myStream = new System.IO.StreamReader(SourceFile))
{
// Process lines while there are lines remaining in the file.
while (!myStream.EndOfStream)
{
if (worker.CancellationPending)
{
e.Cancel = true;
// break;
}
else
{
line1 = myStream.ReadLine();
line2 = (CountInString(line1, CompareString));
LinesCounted1 = (linenumbercount(line1, CompareString, linenumber1));
// Raise an event so the form can monitor progress.
int compare = DateTime.Compare(
DateTime.Now, lastReportDateTime.AddSeconds(elapsedTime));
if (compare > 0)
{
state.LinesCounted = LinesCounted1;
state.line = line2;
worker.ReportProgress(0, state);
lastReportDateTime = DateTime.Now;
}
System.Threading.Thread.Sleep(1);
}
}
// Report the final count values.
state.LinesCounted = LinesCounted1;
state.line = line1;
worker.ReportProgress(0, state);
lastReportDateTime = DateTime.Now;
}
}
}
private string CountInString(
string SourceString,
string CompareString)
{
if (SourceString.Contains(CompareString))
{
line2 = SourceString;
Console.WriteLine(SourceString);
}
return line2;
}
private int linenumbercount(
string SourceString,
string CompareString,
int linenumber)
{
// Lines = 0;
if (SourceString == null)
{
return 0;
}
if (SourceString.Contains(CompareString))
{
Console.WriteLine(linenumber);
}
linenumber++;
return linenumber;
}
}
Any feedback will be helpful. Please let me know what I am doing wrong and where is it that I am making a mistake as I am new to background worker and multithreading. Thanks.
I'm working on a C# UWP APP and I need to communicate with many devices using
an USB port as Serial Port. After that I will convert the communication to RS485 to communicate with the other devices. Until now, I have create a class that will make all comunications between my devices and I can sent a trama between my devices.
My problem at this point is that after sending some startup frames, the application changes the page and from that moment gives me the following exception in my ReadAsync method:
**
System.Exception occurred HResult=-2147023901 Message=The I/O
operation was canceled due to a module output or an application
request. (Exception from HRESULT: 0x800703E3) Source=mscorlib
StackTrace:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at DrDeliver.CComm.d__31.MoveNext() InnerException:
**
Exception Picture
I already have this problem for a few days and I can't get over it.
I wonder if anyone can figure out where the problem is.
Another question I would like to ask is if anyone knows of any method that allows me to make this communication synchronously.
UPDATE 1
The entire class for communicatons:
public class CComm : IDisposable
{
EventLogDB _eldb = new EventLogDB();
ParameterDB _pdb = new ParameterDB();
cParameter _cParam = new cParameter();
DataReader _dataReaderObject = null;
private DispatcherTimer mTimer;
private int num;
public bool FlagComm { set; get; }
public static string InBuffer { set; get; }
public bool busyFlag = false;
public CancellationTokenSource _readCancellationTokenSource = new CancellationTokenSource();
private DeviceInformationCollection DeviceInformation { set; get; }
private static SerialDevice SerialPort { set; get; }
// Define a delegate
public delegate void CheckReadEventHandler(object source, EventArgs args);
// Define an event based on that delegate
public event CheckReadEventHandler CheckRead;
// Raise an event
protected virtual void OnChecRead()
{
CheckRead?.Invoke(this, EventArgs.Empty);
}
private async Task OpenComm()
{
try
{
busyFlag = true;
//_cParam = _pdb.getParameters();
string selectedPortId = null;
string aqs = SerialDevice.GetDeviceSelector();
DeviceInformation = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs);
foreach (var devInfo in DeviceInformation)
{
if (devInfo.Name == "USB-RS485 Cable")
{
selectedPortId = devInfo.Id;
}
}
if (selectedPortId != null)
{
SerialPort = await SerialDevice.FromIdAsync(selectedPortId);
if (SerialPort != null)
{
SerialPort.ReadTimeout = TimeSpan.FromMilliseconds(1500);
SerialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
SerialPort.BaudRate = 9600;
SerialPort.Parity = SerialParity.None;
SerialPort.StopBits = SerialStopBitCount.One;
SerialPort.DataBits = 8;
FlagComm = true;
}
else
{
var status = DeviceAccessInformation.CreateFromId(selectedPortId).CurrentStatus;
FlagComm = false;
_eldb.attachEvent("E1002", "Starting Comunication Failed: " + status);
//ContentDialog noSerialDevice = new ContentDialog()
//{
// Title = "No Serial Connection",
// Content = "Check connection and try again. App Closing.",
//};
//await noSerialDevice.ShowAsync();
//this.Dispose();
}
InitTool();
await ActivateListen();
busyFlag = false;
}
}
catch (Exception ex)
{
_eldb.attachEvent("E1cC", ex.Message);
}
}
private async Task Listen()
{
try
{
if (SerialPort != null)
{
busyFlag = true;
_dataReaderObject = new DataReader(SerialPort.InputStream);
await ReadAsync(_readCancellationTokenSource.Token);
busyFlag = false;
}
}
catch (Exception ex)
{
}
}
//using (var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(1000)))
//{
// await dataReaderObject.LoadAsync(1024).AsTask(cts.Token);
//}
private async Task ReadAsync(CancellationToken cancellationToken)
{
busyFlag = true;
const uint readBufferLength = 1024; // only when this buffer would be full next code would be executed
var loadAsyncTask = _dataReaderObject.LoadAsync(readBufferLength).AsTask(cancellationToken); // Create a task object
_dataReaderObject.InputStreamOptions = InputStreamOptions.ReadAhead;
var bytesRead = await loadAsyncTask; // Launch the task and wait until buffer would be full
if (bytesRead > 0)
{
InBuffer += _dataReaderObject.ReadString(bytesRead);
OnChecRead();
}
busyFlag = false;
}
private async void WriteComm(string str2Send)
{
using (var dataWriter = new DataWriter(SerialPort.OutputStream))
{
dataWriter.WriteString(str2Send);
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
}
private async Task ActivateListen()
{
while (FlagComm)
{
await Listen();
}
}
private void dispatcherTimer_Tick(object sender, object e)
{
_eldb.attachEvent("SYSTEM", "Checking ADDR: " + num);
SendComm(num++, 5);
if (num == 5)
{
mTimer.Stop();
_eldb.attachEvent("SYSTEM", "Modules Checking Finished.");
busyFlag = false;
}
}
public void InitTool()
{
busyFlag = true;
_eldb.attachEvent("SYSTEM", "Setting Parameters.");
// Get Parameters
if (_pdb.GetParameters() == null)
{
// Set Default Parameters
_cParam.SetParam();
// Insert Default parameters in database
_pdb.Insert(_cParam);
// Update Parameters Object
_cParam = _pdb.GetParameters();
}
else
{
// Update Parameters Object
_cParam = _pdb.GetParameters();
}
// Check Addresses in Line
_eldb.attachEvent("SYSTEM", "Start Verifiyng.");
num = 0;
mTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(4000) };
mTimer.Tick += dispatcherTimer_Tick;
mTimer.Start();
}
public async void StartSerialComm()
{
try
{
await OpenComm();
}
catch (Exception ex)
{
_eldb.attachEvent("E7cC", ex.Message);
}
}
public void SendComm(params int[] list)
{
try
{
_cParam = _pdb.GetParameters();
string toSend = "";// = "A" + list[0] + "#";
switch (list[1])
{
case 0:
// Send Initialazation command
toSend = "##" + list[0] + "#" + list[1] + "##";
break;
case 1:
// List of parameters (minPower, maxPower, ramPercent, initSpeed)
toSend = "##" + list[0] + "#" + list[1] + "#" + _cParam.minPower + "#" +
_cParam.maxPower + "#" + _cParam.percRamp + "#" + _cParam.initSpeed + "##";
break;
case 2:
// Send Status Request
toSend = "##" + list[0] + "#" + list[1] + "##";
break;
case 3:
// Send a move Request
toSend = "##" + list[0] + "#" + list[1] + "#" + list[2] + "##";
break;
case 4:
// Send a Error Request
toSend = "##" + list[0] + "#" + list[1] + "##";
break;
case 5:
// Send a start check
toSend = "##" + list[0] + "#" + list[1] + "##";
break;
default:
_eldb.attachEvent("E1004", "Wrong Function Command.");
break;
}
if (toSend != "")
{
WriteComm(toSend);
}
else
{
_eldb.attachEvent("E1003", "Wrong String comunication.");
}
}
catch (Exception ex)
{
_eldb.attachEvent("E8cC", ex.Message);
}
}
public void Dispose()
{
try
{
if (SerialPort == null) return;
FlagComm = false;
SerialPort.Dispose();
SerialPort = null;
if (_dataReaderObject == null) return;
_readCancellationTokenSource.Cancel();
_readCancellationTokenSource.Dispose();
}
catch (Exception ex)
{
_eldb.attachEvent("E6cC", ex.Message);
}
}
}
Main Page:
public sealed partial class MainPage : Page
{
CComm _cC = new CComm();
EventLogDB _eldb = new EventLogDB();
procTrama _cProcTrama = new procTrama();
private DispatcherTimer mTimer;
public MainPage()
{
try
{
InitializeComponent();
// Get the application view title bar
ApplicationViewTitleBar appTitleBar = ApplicationView.GetForCurrentView().TitleBar;
// Make the title bar transparent
appTitleBar.BackgroundColor = Colors.Transparent;
// Get the core appication view title bar
CoreApplicationViewTitleBar coreTitleBar = CoreApplication.GetCurrentView().TitleBar;
/*
ExtendViewIntoTitleBar
Gets or sets a value that specifies whether this title
bar should replace the default window title bar.
*/
// Extend the core application view into title bar
coreTitleBar.ExtendViewIntoTitleBar = true;
mTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(5000) };
mTimer.Tick += dispatcherTimer_Tick;
mTimer.Start();
_eldb.attachEvent("S1027", "Init Started...");
// Start comunication
_cC.StartSerialComm();
// Reference for CheckRead Event
_cC.CheckRead += OnCheckRead;
}
catch (Exception ex)
{
_eldb.attachEvent("MainP", ex.Message);
}
}
private void dispatcherTimer_Tick(object sender, object e)
{
if (!_cC.busyFlag)
{
Frame.Navigate(typeof(InitPage), null);
mTimer.Stop();
}
}
public void OnCheckRead(object source, EventArgs e)
{
try
{
if (CComm.InBuffer == null) return;
_cProcTrama.ProcessTrama(CComm.InBuffer);
CComm.InBuffer = "";
}
catch (Exception ex)
{
_eldb.attachEvent("OnCheckRead: ", ex.Message);
}
}
}
INIT Page:
public partial class InitPage : Page
{
CComm _cC = new CComm();
EventLogDB _eldb = new EventLogDB();
procTrama _cProcTrama = new procTrama();
public InitPage()
{
this.InitializeComponent();
_eldb.attachEvent("S1000", "System Started.");
// Reference for CheckRead Event
_cC.CheckRead += OnCheckRead;
}
private void button_Click(object sender, RoutedEventArgs e)
{
_eldb.attachEvent("S1001", "Login Activated.");
Frame.Navigate(typeof(Page1), null);
}
public void OnCheckRead(object source, EventArgs e)
{
if (CComm.InBuffer == null) return;
_eldb.attachEvent("OnCheckRead: ", CComm.InBuffer);
_cProcTrama.ProcessTrama(CComm.InBuffer);
}
}
Login Page where i more frequently the error occur:
public sealed partial class Page1 : Page
{
private CComm _cC = new CComm();
private procTrama _cProcTrama = new procTrama();
EventLogDB _eldb = new EventLogDB();
public Page1()
{
this.InitializeComponent();
// Reference for CheckRead Event
_cC.CheckRead += OnCheckRead;
user = null;
pass = null;
user_pass = 0;
}
private const int userLimit = 5;
private const int passLimit = 5;
private const char passChar = '*';
public string user
{
get; set;
}
public string pass
{
get; set;
}
public int user_pass
{
get; set;
}
private void execute(char val)
{
string aux = null;
if (user_pass == 1)
{
if (user == null)
user = val.ToString();
else
{
if (user.Length <= userLimit)
user = user + val;
}
userBtn.Content = user;
}
else
{
if (user_pass == 2)
{
if (pass == null)
pass = val.ToString();
else
{
if (pass.Length <= passLimit)
pass = pass + val;
}
for (int i = 0; i < pass.Length; i++)
aux = aux + passChar;
passBtn.Content = aux;
}
}
}
private void key1Btn_Click(object sender, RoutedEventArgs e)
{
execute('1');
}
private void key2Btn_Click(object sender, RoutedEventArgs e)
{
execute('2');
}
private void key3Btn_Click(object sender, RoutedEventArgs e)
{
execute('3');
}
private void key4Btn_Click(object sender, RoutedEventArgs e)
{
execute('4');
}
private void key5Btn_Click(object sender, RoutedEventArgs e)
{
execute('5');
}
private void key6Btn_Click(object sender, RoutedEventArgs e)
{
execute('6');
}
private void key7Btn_Click(object sender, RoutedEventArgs e)
{
execute('7');
}
private void key8Btn_Click(object sender, RoutedEventArgs e)
{
execute('8');
}
private void key9Btn_Click(object sender, RoutedEventArgs e)
{
execute('9');
}
private void key0Btn_Click(object sender, RoutedEventArgs e)
{
execute('0');
}
private void keyEntrarBtn_Click(object sender, RoutedEventArgs e)
{
if (pass == "123" && user == "123")
{
_eldb.attachEvent("S1002", "User Login: " + user);
Frame.Navigate(typeof(Page2), null);
}
user_pass = 0;
passBtn.Content = "Insirir Código";
userBtn.Content = "Inserir Utilizador";
}
private void keyApagarBtn_Click(object sender, RoutedEventArgs e)
{
pass = null;
user = null;
user_pass = 0;
passBtn.Content = "Inserir Código";
userBtn.Content = "Inserir Utilizador";
_eldb.attachEvent("S1003", " User data cleared.");
}
private void userBtn_Click(object sender, RoutedEventArgs e)
{
user_pass = 1;
userBtn.Content = "";
_eldb.attachEvent("S1004", "User button clicked.");
}
private void passBtn_Click(object sender, RoutedEventArgs e)
{
user_pass = 2;
passBtn.Content = "";
_eldb.attachEvent("S1005", "Pass button clicked.");
}
private void exitBtn_Click(object sender, RoutedEventArgs e)
{
_eldb.attachEvent("S1006", "Page1 exit button clicked.");
Frame.Navigate(typeof(InitPage), null);
}
public void OnCheckRead(object source, EventArgs e)
{
try
{
if (CComm.InBuffer == null) return;
_eldb.attachEvent("OnCheckRead: ", CComm.InBuffer);
_cProcTrama.ProcessTrama(CComm.InBuffer);
}
catch (Exception ex)
{
_eldb.attachEvent("OnCheckRead: ", ex.Message);
}
}
}
I'm developing an application for a windows CE 6.0 scanner device and I'm having an issue when I want to insert datas.
I'm using the OpenNETCF.ORM framework and SQLite.
The problem happens when I want to add a 3rd article to the database with the insert() method. It works well with the first 2 articles but when it comes to the 3rd one, it throws an exception which is "SQLiteConnection".
Did anyone have the same issue with this ORM framework and could help me pls?
Here is the code of DatabaseHelper.cs :
using System;
using System.Windows.Forms;
using OpenNETCF.ORM;
namespace OfflineWMS
{
public class DatabaseHelper
{
private Scanner _scannerManager = new Scanner();
private static DatabaseHelper _instance = null;
private static readonly object MyLock = new object();
private SQLiteDataStore _stockDatabase;
public SQLiteDataStore StockDatabase1
{
get { return _stockDatabase; }
set { _stockDatabase = value; }
}
private DatabaseHelper() {}
public static DatabaseHelper getInstance()
{
lock (MyLock)
{
if (_instance == null)
{
_instance = new DatabaseHelper();
_instance.InitDatabase();
}
return _instance;
}
}
//Create the Database
public void InitDatabase()
{
StockDatabase1 = new SQLiteDataStore(ConfigurationHelper.Settings["PathToTheApp"] + ConfigurationHelper.Settings["DatabaseFilename"]);
if (!StockDatabase1.StoreExists)
{
StockDatabase1.CreateStore();
}
InitializeDbStructure();
}
private void InitializeDbStructure()
{
StockDatabase1.AddType<Article>();
}
}
}`
The code in the Form.cs where I have the issue (at the end of the code) :
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using FileOperations.CsvImport;
using FileOperations.CsvImport.FluentInterface;
using OfflineWMS.Properties;
using OpenNETCF.ORM;
using Symbol.Barcode;
namespace OfflineWMS
{
public partial class Form1 : Form
{
private ReaderData TheReaderData;
private Scanner ScannerManager;
private bool IsReaderInitiated;
private DatabaseHelper db;
public Form1()
{
InitializeComponent();
}
protected override void OnClosing(CancelEventArgs e)
{
if (IsReaderInitiated)
ScannerManager.TermReader();
base.OnClosing(e);
}
private void ScannerManager_ReadNotify(object sender, EventArgs e)
{
TheReaderData = ScannerManager.Reader1.GetNextReaderData();
//action to do
ProcessData(TheReaderData);
ScannerManager.StopRead();
ScannerManager.StartRead(true);
}
private void ProcessData(ReaderData TheReaderData)
{
if (TheReaderData != null)
{
textBox1.Text = TheReaderData.Text;
}
else
{
MessageBox.Show(Resources.ReaderDataIsNull);
}
}
private void ScannerManager_StatusNotify(object sender, EventArgs e)
{
BarcodeStatus theStatus = ScannerManager.Reader1.GetNextStatus();
if (theStatus != null)
{
switch (theStatus.State)
{
case States.IDLE:
statusBar1.Text = Resources.IDLEStatus;
break;
case States.READY:
statusBar1.Text = Resources.ReadyStatus;
break;
case States.WAITING:
statusBar1.Text = Resources.WaitingStatus;
break;
default:
statusBar1.Text = Resources.DefaultStatus;
break;
}
}
else
{
//log error
}
}
protected override void OnLoad(EventArgs e)
{
// DatabaseHelper is instanciated only once here
db = DatabaseHelper.getInstance();
ScannerManager = new Scanner();
IsReaderInitiated = ScannerManager.InitReader();
textBox1.Focus();
// if not initialized, we quit the app
if (!IsReaderInitiated)
{
MessageBox.Show(Resources.InitiatingError);
Application.Exit();
}
else
{
ScannerManager.AttachStatusNotify(ScannerManager_StatusNotify);
ScannerManager.StartRead(true);
ScannerManager.AttachReadNotify(ScannerManager_ReadNotify);
}
//db.InitDatabase();
base.OnLoad(e);
}
private void buttonAddToDb_Click(object sender, EventArgs e)
{
if ((TheReaderData != null))
{
var article = new Article
{
ArticleName = "test",
ArticleCode = "321",
ArticleFeature = "true blue",
ArticlePrice = 33.22m,
ArticleQuantity = 15,
ArticleBarcode = TheReaderData.Text
};
var article2 = new Article
{
ArticleName = "test",
ArticleCode = "321",
ArticleFeature = "true blue",
ArticlePrice = 33.22m,
ArticleQuantity = 15,
ArticleBarcode = TheReaderData.Text
};
var article3 = new Article
{
ArticleName = "test",
ArticleCode = "321",
ArticleFeature = "true blue",
ArticlePrice = 33.22m,
ArticleQuantity = 15,
ArticleBarcode = TheReaderData.Text
};
// HERE
try
{
db.StockDatabase1.Insert(article);// article added
db.StockDatabase1.Insert(article2);// article2 added
db.StockDatabase1.Insert(article3);// throws the exception "SQLiteException"
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
ScannerManager.TermReader();
Application.Exit();
}
else
{
MessageBox.Show(Resources.ScanData);
}
}
}
}
And this is the stacktrace of this SQLiteException :
at System.Data.SQLite.SQLiteConnection.CheckDisposed()
at System.Data.SQLite.SQLiteConnection.get_State()
at OpenNETCF.ORM.SQLStoreBase`1.<GetPoolConnection>b__11(IDbConnection c)
at System.Linq.Enumerable.<WhereIterator>d__0`1.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
at OpenNETCF.ORM.SQLStoreBase`1.GetPoolConnection()
at OpenNETCF.ORM.SQLStoreBase`1.GetConnection(Boolean maintenance, Boolean isRetry)
at OpenNETCF.ORM.SQLStoreBase`1.GetConnection(Boolean maintenance)
at OpenNETCF.ORM.SQLiteDataStore.OnInsert(Object item, Boolean insertReferences)
at OpenNETCF.ORM.DataStore`1.Insert(Object item, Boolean insertReferences, Boolean recoveryInsert)
at OpenNETCF.ORM.DataStore`1.Insert(Object item, Boolean insertReferences)
at OpenNETCF.ORM.DataStore`1.Insert(Object item)
at OfflineWMS.Form1.buttonAddToDb_Click(Object sender, EventArgs e)
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.ButtonBase.WnProc(WM wm, Int32 wParam, Int32 lParam)
at System.Windows.Forms.Control._InternalWnProc(WM wm, Int32 wParam, Int32 lParam)
at Microsoft.AGL.Forms.EVL.EnterMainLoop(IntPtr hwnMain)
at System.Windows.Forms.Application.Run(Form fm)
at OfflineWMS.Program.Main()
USB thumb drives
USB harddisks
USB DVD writer
USB Bluetooth devices
USB headsets
usb mouse
USB keyboard
USB webcams / cameras
Just want to detect any sort of usb device using event handler...
Would appreciate any help...
WqlEventQuery q_creation = new WqlEventQuery();
private void Form2_Load(object sender, EventArgs e)
{
q_creation.EventClassName = "__InstanceCreationEvent";
q_creation.WithinInterval = new TimeSpan(0, 0, 2); //How often do you want to check it? 2Sec.
q_creation.Condition = #"TargetInstance ISA 'Win32_DiskDriveToDiskPartition'";
var mwe_creation = new ManagementEventWatcher(q_creation);
mwe_creation.EventArrived += new EventArrivedEventHandler(USBEventArrived_Creation);
mwe_creation.Start(); // Start listen for events
}
/// <summary>
/// Callback event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
internal void USBEventArrived_Creation(object sender, EventArrivedEventArgs e)
{
MessageBox.Show("Device Connected");
}
This is the code what i had tried.
I am pasting my entire class for you, use as is (hookup the events right at the bottom for detecting or removal of USB) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace BlueMercs.Core.Services.WMI
{
public class EventUsbMonitorEvent : EventArgs
{
public string Model { get; set; }
public string Drive { get; set; }
}
public class UsbMonitor
{
private const string _queryForEvents = #"SELECT * FROM __InstanceOperationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_DiskDrive'";
private string _queryDiskPartitionDevice = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=\"{0}\"} WHERE AssocClass = Win32_DiskDriveToDiskPartition";
private string _queryDiskLogicalPartition = "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=\"{0}\"} WHERE AssocClass = Win32_LogicalDiskToPartition";
private readonly ManagementEventWatcher _watcher;
private Thread _thread;
public UsbMonitor()
{
_watcher = new ManagementEventWatcher();
var query = new WqlEventQuery(_queryForEvents);
_watcher.EventArrived += Watcher_EventArrived;
_watcher.Query = query;
}
public void Start()
{
_watcher.Start();
_thread = new Thread(Listen);
_thread.Start();
}
public void Stop()
{
try { _thread.Abort(); } catch { } //suppress thread abort exception
_watcher.Stop();
}
private void Listen()
{
_watcher.WaitForNextEvent();
Listen();
}
private string GetDriveLetterFromDisk(string name)
{
name = name.Replace(#"\", #"\\");
var driveLetter = string.Empty;
var qryPartition = new ObjectQuery("ASSOCIATORS OF {Win32_DiskDrive.DeviceID=\"" + name + "\"} WHERE AssocClass = Win32_DiskDriveToDiskPartition"); //string.Format(_queryDiskPartitionDevice, name));
var partition = new ManagementObjectSearcher(qryPartition);
foreach (var result in partition.Get())
{
//var qryLogicalDisk = new ObjectQuery(string.Format(_queryDiskLogicalPartition, result["DeviceID"]));
var logicalDisk = new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID=\"" + result["DeviceID"] + "\"} WHERE AssocClass = Win32_LogicalDiskToPartition"); //qryLogicalDisk);
driveLetter = logicalDisk.Get().Cast<ManagementBaseObject>().Aggregate(driveLetter, (current, x) => current + (x["Name"] + ","));
}
return driveLetter.Trim(',');
}
private void Watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject targetInstance;
switch (e.NewEvent.ClassPath.ClassName)
{
case "__InstanceCreationEvent":
targetInstance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
if (targetInstance["InterfaceType"].ToString() == "USB")
{
var driveName = targetInstance["Caption"].ToString();
var driveLetter = GetDriveLetterFromDisk(targetInstance["Name"].ToString());
if (OnExternalUsbDetected != null)
OnExternalUsbDetected(this, new EventUsbMonitorEvent { Model = driveName, Drive = driveLetter });
}
break;
case "__InstanceDeletionEvent":
targetInstance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
if (targetInstance["InterfaceType"].ToString() == "USB")
{
var driveName = targetInstance["Caption"].ToString();
var driveLetter = GetDriveLetterFromDisk(targetInstance["Name"].ToString());
if (OnExternalUsbRemoved != null)
OnExternalUsbRemoved(this, new EventUsbMonitorEvent { Model = driveName, Drive = driveLetter });
}
break;
}
}
public event EventHandler<EventUsbMonitorEvent> OnExternalUsbDetected;
public event EventHandler<EventUsbMonitorEvent> OnExternalUsbRemoved;
}
}