'
public partial class ComPortForm : Form
{
//Port Numaralarını ports isimli diziye atıyoruz.
string[] ports = SerialPort.GetPortNames();
public ComPortForm(SerialPort SP)
{
InitializeComponent();
}
private void ComPortForm_Load(object sender, EventArgs e)
{
foreach (string port in ports)
{
// Port isimlerini combobox1'de gösteriyoruz.
comboBox1.Items.Add(port);
comboBox1.SelectedIndex = 0;
}
// Baudrate'leri kendimiz combobox2'ye giriyoruz.
comboBox2.Items.Add("2400");
comboBox2.Items.Add("4800");
comboBox2.Items.Add("9600");
comboBox2.Items.Add("19200");
comboBox2.Items.Add("115200");
comboBox2.SelectedIndex = 2;
//Bu esnada bağlantı yok.
label1.Text = "Bağlantı Kapalı";
}
private void ComPortForm_Load(object sender, FormClosingEventArgs e)
{
// Form kapandığında Seri Port Kapatılmış Olacak.
if (Program.serial.IsOpen == true)
{
Program.serial.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
if (Program.serial.IsOpen == false)
{
if (comboBox1.Text == "")
return;
// combobox1'e zaten port isimlerini aktarmıştık.
Program.serial.PortName = comboBox1.Text;
//Seri Haberleşme baudrate'i combobox2 'de seçilene göre belirliyoruz.
Program.serial.BaudRate = Convert.ToInt16(comboBox2.Text);
try
{
//Haberleşme için port açılıyor
Program.serial.Open();
label1.ForeColor = Color.Green;
label1.Text = "Bağlantı Açık.";
}
catch (Exception hata)
{
MessageBox.Show("Hata:" + hata.Message);
}
}
else
{
label1.Text = "Bağlantı Zaten Açık!";
}
}
private void button2_Click(object sender, EventArgs e)
{
//BAĞLANTIYI KES BUTONU
timer1.Stop();
if (Program.serial.IsOpen == true)
{
Program.serial.Close();
label1.BackColor = Color.Transparent;
label1.ForeColor = Color.Red;
label1.Text = "Bağlantı Kapalı.";
}
}
private void button3_Click(object sender, EventArgs e)
{
//kaydet butonuyla Form2'yi kapatıyoruz.
this.Close();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
//resim kutusuna dokununca url ye gidecek.
System.Diagnostics.Process.Start("explorer.exe", #"https://hosseven.com.tr/");
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
'
My application for which I selected the Serial Port settings is currently running, but I want to save these settings and use them when my application starts again.I want to keep my chosen settings between application starts? Do I need to save to json file? please edit my code and help.I'm new at this job.
Related
I will be glad if you tell me what I need to edit on the code. I want to separate the data I receive byte by byte, how do I do it?
namespace _1993
{
public partial class Form1 : Form
{
string[] ports = SerialPort.GetPortNames(); //Port Numaralarını ports isimli diziye atıyoruz.
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (string port in ports)
{
comboBox1.Items.Add(port); // Port isimlerini combobox1'de gösteriyoruz.
comboBox1.SelectedIndex = 0;
}
comboBox2.Items.Add("2400"); // Baudrate'leri kendimiz combobox2'ye giriyoruz.
comboBox2.Items.Add("4800");
comboBox2.Items.Add("9600");
comboBox2.Items.Add("19200");
comboBox2.Items.Add("115200");
comboBox2.SelectedIndex = 2;
label3.Text = "Bağlantı Kapalı"; //Bu esnada bağlantı yok.
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Form kapandığında Seri Port Kapatılmış Olacak.
if (serialPort1.IsOpen == true)
{
serialPort1.Close();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
try
{
string sonuc = serialPort1.ReadExisting();//Serial.print kodu ile gelen analog veriyi alıyoruz,string formatında sonuc'a atıyoruz
if (sonuc != "")
{
label1.Text = sonuc + ""; //Labele yazdırıyoruz.
listBox1.Items.Add(sonuc); //labele yazdırdığını listboxa ekle
byte[] ba = Encoding.Default.GetBytes(sonuc);
var hexString = BitConverter.ToString(ba);
if (ba[0] == 0XFF)
{
Console.WriteLine(ba);
}
else
{
Console.WriteLine("hatalı");
}
//Console.WriteLine(ba[0]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); // basarısız olursa hata verecek.
timer1.Stop();
}
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Start(); //250 ms olarak ayarladım timer'ı.
if (serialPort1.IsOpen == false)
{
if (comboBox1.Text == "")
return;
serialPort1.PortName = comboBox1.Text; // combobox1'e zaten port isimlerini aktarmıştık.
serialPort1.BaudRate = Convert.ToInt16(comboBox2.Text); //Seri Haberleşme baudrate'i combobox2 'de seçilene göre belirliyoruz.
try
{
serialPort1.Open(); //Haberleşme için port açılıyor
label3.ForeColor = Color.Green;
label3.Text = "Bağlantı Açık";
}
catch (Exception hata)
{
MessageBox.Show("Hata:" + hata.Message);
}
}
else
{
label3.Text = "Bağlantı kurulu !!!";
}
}
private void button2_Click(object sender, EventArgs e)
{
//BAĞLANTIYI KES BUTONU
timer1.Stop();
if (serialPort1.IsOpen == true)
{
serialPort1.Close();
label3.ForeColor = Color.Red;
label3.Text = "Bağlantı Kapalı";
}
}
private void button3_Click(object sender, EventArgs e)
{
listBox1.Items.Add(label1.Text); //Okunan veri listbox'a atılıyor
}
private void button4_Click(object sender, EventArgs e)
{
listBox1.Items.Clear(); // listbox temizleniyor.
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
SerialPort already returns bytes reads and returns bytes. ReadExisting converts those bytes to a string using the SerialPort.Encoding. To get the raw bytes use Read or ReadByte instead :
var buffer=byte[1024];
var read=port.Read(buffer,0,buffer.Length);
if (read>0 && buffer[0] == 0XFF)
{
....
}
You'll have to convert the bytes to a string explicitly using Encoding.GetString if you want to display the or write them to the console. :
var str=SerialPort.Encoding.GetString(buffer,0,read);
Be careful though.
The default for SerialPort.Encoding is ASCIIEncoding, the 7-bit US-ASCII encoding. This will mangle all non-Latin characters. If the port returnes non-US-ASCII text you'll have to find the proper encoding and use it. On a POS this would mangle non-English product names.
I've written desktop application, that receives location via serial communication from NRF/GPS module, split that data in order to distinguish latitude, longitude and then i load these coordinates to map(i use GMap). But when i receive data, first 1 or 2 seconds it comes in a little confused form(like this 06840.370056;49.84006068). And i thought adding some Thread.Sleep will solve this problem, but instead application crashes after 5-10 seconds. How can i solve this problem, because i want my app run smoothly? Here is part of my code:
public partial class Form1 : Form
{
public string dataIn;
private List<PointLatLng> _points;
public Form1()
{
_points = new List<PointLatLng>();
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GMapProviders.GoogleMap.ApiKey = AppConfig.Key;
string[] ports = SerialPort.GetPortNames();
cBoxCom.Items.AddRange(ports);
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
gMap.MapProvider = GMapProviders.GoogleMap;
gMap.ShowCenter = false;
gMap.DragButton = MouseButtons.Left;
gMap.SetPositionByKeywords("Chennai, India");
}
private void btnConnect_Click(object sender, EventArgs e)
{
serialPort1.PortName = cBoxCom.Text;
serialPort1.BaudRate = Convert.ToInt32(cBoxBaudrate.Text);
btnConnect.Enabled = false;
btnDisconnect.Enabled = true;
serialPort1.Open();
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
}
}
private void btnClearDataIn_Click(object sender, EventArgs e)
{
if (richBoxReciever.Text != "")
{
richBoxReciever.Text = " ";
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
dataIn = serialPort1.ReadExisting();
this.Invoke(new EventHandler(ShowData));
}
private void ShowData(object sender, EventArgs e)
{
Thread.Sleep(3000);
richBoxReciever.Text += dataIn;
Thread.Sleep(5000);
string[] locationData = dataIn.Split(new char[] { ';' });
List<string> tokens = new List<string>();
foreach (string s in locationData)
{
if (s.Length != 0)
{
tokens.Add(s);
}
}
txtLat.Text = tokens[0];
txtLon.Text = tokens[1];
}
No response from the command line is displayed when JLink.exe starts, nothing happens when the "ReadMemory" button is pressed.
But if after that you enter the command "exit" all the operations performed on the command line are displayed.
How can you fix this and why is it happening?
public partial class MainWindow : Window
{
Process jLinkProcess = new Process();
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
jLinkProcess.StartInfo = new ProcessStartInfo(#"C:\Program Files\SEGGER\JLink\JLink.exe");
jLinkProcess.StartInfo.UseShellExecute = false;
jLinkProcess.StartInfo.RedirectStandardInput = true;
jLinkProcess.StartInfo.RedirectStandardOutput = true;
jLinkProcess.StartInfo.RedirectStandardError = true;
jLinkProcess.StartInfo.CreateNoWindow = true;
jLinkProcess.OutputDataReceived += CmdProcess_OutputDataReceived;
jLinkProcess.ErrorDataReceived += CmdProcess_ErrorDataReceived;
jLinkProcess.Start();
jLinkProcess.BeginOutputReadLine();
jLinkProcess.BeginErrorReadLine();
jLinkProcess.StandardInput.WriteLine("connect");
jLinkProcess.StandardInput.WriteLine("NRF52811_XXAA");
jLinkProcess.StandardInput.WriteLine("SWD");
jLinkProcess.StandardInput.WriteLine("4000");
}
private void CmdProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Dispatcher.Invoke(() =>
{
TextBox2.Text += e.Data + "\r\n";
TextBox2.ScrollToEnd();
});
}
private void CmdProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Dispatcher.Invoke(() =>
{
TextBox2.Text += e.Data + "\r\n";
TextBox2.ScrollToEnd();
});
}
private void TextBox1_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (sender is TextBox textBox && e.Key == Key.Enter)
{
jLinkProcess.StandardInput.WriteLine(textBox.Text);
textBox.Text = string.Empty;
e.Handled = true;
}
}
private void ReadMemory(object sender, RoutedEventArgs e)
{
string mac = "mem 10000060,8";
jLinkProcess.StandardInput.WriteLine(mac);
}
}
Currently i am having trouble updating a row in my listview that contains both text and a timer that counts down. So far I've tried updating the entire row as well as trying to update just the text and i get an error in each instance.
System.ArgumentOutOfRangeException: InvalidArgument=Value of '0' is not valid for 'index
I am also having a slight problem with the delete button. It deletes the row as planned but it appears the information is still running in the background and haven't come across any info on how to delete the session. I pray for your guidance.
private void Confirm_Click(object sender, EventArgs e)
{
CSession newSession = new CSession();
if(PasswordText.Text == "")
{
MessageBox.Show("Password not entered");
return;
}
newSession.password = PasswordText.Text;
newSession.purchased_time = workingTimeSpan;
newSession.remaining_time = workingTimeSpan;
newSession.status = "Online";
sessionlist.Add(newSession);
PasswordText.Text = "";
TimerLabel.Text = "";
workingTimeSpan = new TimeSpan();
}
private void DisplayAllSessions()
{
listView1.Items.Clear();
foreach(CSession c in sessionlist)
{
string[] row = { c.password, c.purchased_time.ToString(), c.remaining_time.ToString(), c.status };
ListViewItem i = new ListViewItem(row);
listView1.Items.Add(i);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
foreach(CSession c in sessionlist)
{
if (c.remaining_time.TotalMinutes == 5 && !c.MessageDisplayed)
{
c.MessageDisplayed = true;
MessageBox.Show("Time almost up for client.");
}
if (c.remaining_time.TotalSeconds < 1)
{
c.status = "Offline";
}
if(c.status == "Online")
{
c.remaining_time -= oneSecond;
}
}
DisplayAllSessions();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void Reset_Click(object sender, EventArgs e)
{
}
private void updatebutton()
{
listView1.SelectedItems[0].SubItems[0].Text = PasswordText.Text;
PasswordText.Text = "";
}
private void Update_Click(object sender, EventArgs e)
{
updatebutton();
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
PasswordText.Text = listView1.SelectedItems[0].Text;
TimerLabel.Text = listView1.SelectedItems[0].SubItems[1].Text;
}
private void Delete_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you wish to delete.", "Removing User", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
listView1.Items.Clear();
timer1.Stop();
}
}
This is what i used for the update function and delete row function.
private void updatebutton()
{
CSession updatedsession = new CSession();
int updateindex = 0;
int index = 0;
foreach (CSession lookup in sessionlist)
{
if(lookup.password == PasswordText.Text)
{
if (MessageBox.Show("Do you wish to add time.", "Adding Time",
MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
updatedsession = lookup;
updateindex = index;
}
break;
}
index++;
}
updatedsession.purchased_time = workingTimeSpan +
updatedsession.purchased_time;
updatedsession.remaining_time = workingTimeSpan +
updatedsession.remaining_time;
sessionlist[updateindex] = updatedsession;
//sortedSessionList[PasswordText.Text] = updatedsession;
PasswordText.Text = "";
TimerLabel.Text = "";
workingTimeSpan = new TimeSpan();
}
private void Update_Click(object sender, EventArgs e)
{
updatebutton();
}
private void Delete_Click(object sender, EventArgs e)
{
CSession cSession = new CSession();
if (MessageBox.Show("Do you wish to delete.", "Removing User",
MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
int index = 0;
foreach (CSession c in sessionlist)
{
if(c.password == PasswordText.Text)
{
break;
}
index++;
}
sessionlist.RemoveAt(index);
}
}
I'm new to C# development. I'm working on a Server Client Chat application and I wish to enable image exchanging feature between the server and the client. I've tried alot of online tutorials but none adjusts to my code. Following is my code:
namespace ServerClientChat
{
{
public partial class Form1 : Form
{
private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string receive;
public Image img_to_receive;
public String text_to_send;
public Image img_to_send;
public String UserName = "Asad";
public Form1()
{
InitializeComponent();
IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName()); //getting own IP
foreach (IPAddress address in localIP)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
textBox3.Text = address.ToString();
}
}
// textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
}
private void button3_Click(object sender, EventArgs e) //Connect to server
{
if (string.IsNullOrWhiteSpace(this.textBox7.Text))
{
MessageBox.Show("Please enter a Username.");
}
else if (string.IsNullOrWhiteSpace(this.textBox5.Text))
{
MessageBox.Show("Please enter an IP address.");
}
else if (string.IsNullOrWhiteSpace(this.textBox6.Text))
{
MessageBox.Show("Please enter a Port number.");
}
else
{
textBox7.Enabled = false;
textBox2.Enabled = false;
textBox5.Enabled = false;
textBox6.Enabled = false;
client = new TcpClient();
//set client side endpoint consisting of client's ip address and port
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text), int.Parse(textBox6.Text));
try
{
client.Connect(IP_End);
if (client.Connected)
{
textBox2.AppendText(">> Connected to Server" + "\n");
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync(); //start receiving data in background (async means non-blocked communication
backgroundWorker2.WorkerSupportsCancellation = true; //ability to cancel this thread
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
private void button2_Click(object sender, EventArgs e) //Start server
{
if (string.IsNullOrWhiteSpace(this.textBox7.Text))
{
MessageBox.Show("Please enter a Username.");
}
else if (string.IsNullOrWhiteSpace(this.textBox4.Text))
{
MessageBox.Show("Please enter a Port number.");
}
else
{
textBox7.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
textBox2.Enabled = false;
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text)); //Listens for connections from TCP network clients.
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream()); //Implements a TextReader that reads characters from a byte stream in a particular encoding.
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true; //Setting AutoFlush to true means that data will be flushed from the buffer to the stream after each write operation, but the encoder state will not be flushed.
backgroundWorker1.RunWorkerAsync(); //start receiving data in background (async means non-blocked communication
backgroundWorker2.WorkerSupportsCancellation = true; //ability to cancel this thread
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //to receive data
{
while(client.Connected)
{
try
{
receive = STR.ReadLine();
this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.AppendText( receive + "\n\n"); }));
receive = "";
}
catch(Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) //to send data
{
if(client.Connected)
{
STW.WriteLine(text_to_send);
this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.AppendText(text_to_send + "\n\n"); }));
}
else
{
MessageBox.Show("Send Failed");
}
backgroundWorker2.CancelAsync();
}
private void button1_Click(object sender, EventArgs e) //Send button
{
if(textBox1.Text!="")
{
text_to_send = textBox7.Text+":"+textBox1.Text;
backgroundWorker2.RunWorkerAsync();
}
textBox1.Text = "";
}
private void Form1_Load(object sender, EventArgs e)
{
DialogResult f = MessageBox.Show("Welcome to My Chat App! Do you want to start your own Server? ", "Welcome!", MessageBoxButtons.YesNoCancel);
if (f == DialogResult.Yes)
{
button3.Enabled = false;
textBox5.Enabled = false;
textBox6.Enabled = false;
}
if (f == DialogResult.No)
{
button2.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
}
if(f==DialogResult.Cancel)
{
this.Close();
}
}
private void label5_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1_Click(this, new EventArgs());
}
}
private void button4_Click(object sender, EventArgs e)
{
}
private void browsebtn_Click(object sender, EventArgs e)
{
}
private void sendimg_Click(object sender, EventArgs e)
{
try
{
}
catch(Exception c)
{
MessageBox.Show(c.Message);
}
}
}
}