Losing \n when sent to other form c# - c#

I am working on a project where im supposed to send a list of titles to a "central computer".
My problem is that when I send them with the button sendAll I lose a couple och linebreaks.
Anyone got some advice on how to get this to work?
Since this is a school assignment I cant access the "central computer". I can only work with my own program.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Avdelningsrapport
{
public partial class KlientForm : Form
{
TcpClient client = new TcpClient();
int port = 12345;
FileLoader fileLoader = new FileLoader();
List<Book> ListOfBooks = FileLoader.BookIndex;
public KlientForm()
{
InitializeComponent();
client.NoDelay = true;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnImportData_Click(object sender, EventArgs e)
{
foreach (Book item in ListOfBooks)
{
listBoxObj.Items.Add(item);
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
if (!client.Connected) StartConnection();
if (client.Connected)
{
btnConnect.BackColor = Color.Green;
}
}
public async void StartConnection()
{
try
{
IPAddress adress = IPAddress.Parse("127.0.0.1");
await client.ConnectAsync(adress, port);
}
catch (Exception error) { MessageBox.Show(error.Message, Text); return;}
btnConnect.Enabled = false;
btnSendAll.Enabled = true;
btnSendMarked.Enabled = true;
}
private void btnSendAll_Click(object sender, EventArgs e)
{
if (!client.Connected)
{
MessageBox.Show("Du måste ansluta till servern.");
}
else
{
if (listBoxObj.Items.Count == 0)
{
MessageBox.Show("Det finns inga böcker att skicka.");
}
else
{
foreach (Book item in listBoxObj.Items)
{
StartSend(item.ToString());
}
ListOfBooks.Clear();
listBoxObj.Items.Clear();
}
}
}
private void btnSendMarked_Click(object sender, EventArgs e)
{
if (!client.Connected)
{
MessageBox.Show("Du måste ansluta till servern.");
}
else
{
if (listBoxObj.SelectedIndex == -1)
{
MessageBox.Show("Du måste välja en bok du vill skicka.");
}
else
{
StartSend(listBoxObj.SelectedItem.ToString());
ListOfBooks.RemoveAt(listBoxObj.SelectedIndex);
listBoxObj.Items.RemoveAt(listBoxObj.SelectedIndex);
}
}
}
public async void StartSend(string SendingBook)
{
byte[] outData = Encoding.Unicode.GetBytes(SendingBook);
try
{
await client.GetStream().WriteAsync(outData, 0, outData.Length);
}
catch (Exception error) { MessageBox.Show(error.Message, Text); return; }
}
}
}

Related

How do I fix "Operation not allowed on unconnected sockets"?

For a school project, I have to create a simple desktop chat app. I've gone for a client-server approach. After doing some research on TCP listeners and clients and following a few tutorials I produced the following 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.Net;
using System.Net.Sockets;
using System.IO;
namespace NetworkTest
{
public partial class Form1 : Form
{
private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string recieve;
public string TextToSend;
public Form1()
{
InitializeComponent();
IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName());
foreach(IPAddress address in localIP)
{
if(address.AddressFamily == AddressFamily.InterNetwork)
{
IPBox1.Text = address.ToString();
}
}
}
private void StartButton_Click(object sender, EventArgs e)
{
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(PortBox1.Text));
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker2.WorkerSupportsCancellation = true;
}
private void ConnectButton_Click(object sender, EventArgs e)
{
client = new TcpClient();
IPEndPoint IpEnd = new IPEndPoint(IPAddress.Parse(IPBox2.Text), int.Parse(PortBox2.Text));
try
{
ChatScreenBox.AppendText("Connect to Server" + "\n");
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker2.WorkerSupportsCancellation = true;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (client.Connected)
{
try
{
recieve = STR.ReadLine();
this.ChatScreenBox.Invoke(new MethodInvoker(delegate ()
{
ChatScreenBox.AppendText("You: " + recieve + "\n");
}));
recieve = "";
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
if (client.Connected)
{
STW.WriteLine(TextToSend);
this.ChatScreenBox.Invoke(new MethodInvoker(delegate()
{
ChatScreenBox.AppendText("Me: " + TextToSend + "\n");
}));
}
else
{
MessageBox.Show("Sending Failed");
}
backgroundWorker2.CancelAsync();
}
private void SendButton_Click(object sender, EventArgs e)
{
if(MessageTextBox.Text != "")
{
TextToSend = MessageTextBox.Text;
backgroundWorker2.RunWorkerAsync();
}
MessageTextBox.Text = "";
}
}
}
UI: https://ibb.co/jk2HRcJ
In theory it should work however as soon as I try to send a message I get the alert "Operation not allowed on unconnected sockets".
Why is this? And how can I resolve this issue?
Thank you in advance
.
As the error says, you must create a connection before you can operate on it.
For socket, I once wrote a detailed sample tutorial, you can refer to it.
If you have any questions about this,please comment bellow and I'll check it out.

Communication between 2 Form in C#(Keep connecting from Fom1 for Form2) [duplicate]

This question already has answers here:
Communicate between two windows forms in C#
(12 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I am a newbie in C# and I have questions as below:
I have a Form1 name is setting Port Name, Baud Rate, Parity... of modbus protocol and I can open serial Port.
Also, I have another Form is called Form2, When Port is opened i want to close Form1 and Port alway Open => I can do it. But this problem that was I want to get data such as FC03 HolodingRegister, FC01 WriteSingleCoil... for Form2 but didnot.
I used delegate to transfer data from Form 1 to Form 2 but I could not use button Form2 to send FC01 signal.
How to use FC01, FC03,04... for Form2 when Form 1 connected.
Code Form1:
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.Ports;
using Modbus.Device;
namespace ATS
{
public partial class frCommunication : Form
{
SerialPort serialPort = new SerialPort();
ModbusMaster Master;
public delegate void truyendulieu(string text);
public truyendulieu truyendata;
public delegate void truyendulieu1(string text1);
public truyendulieu1 truyendata1;
public delegate void truyendulieu2(string text2);
public truyendulieu2 truyendata2;
public frCommunication()
{
InitializeComponent();
}
private void frCommunication_Load(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
cboxPort.Items.AddRange(ports);
cboxPort.SelectedIndex = 0;
}
private void btnConnect_Click(object sender, EventArgs e)
{
btnConnect.Enabled = false;
btnDisconnect.Enabled = true;
try
{
serialPort.PortName = cboxPort.Text;
serialPort.BaudRate = Convert.ToInt32(cboxBaudRate.Text);
serialPort.DataBits = Convert.ToInt32(cboxDataBits.Text);
serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboxStopBits.Text);
serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboxParity.Text);
serialPort.Open();
Master = ModbusSerialMaster.CreateRtu(serialPort);
Master.Transport.Retries = 0; // don't have to to retries
Master.Transport.ReadTimeout = 300;//miliseconds
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (serialPort.IsOpen)
{
lblDisplay.Text = "Connected";
lblDisplay.ForeColor = System.Drawing.Color.Red;
cboxBaudRate.Enabled = false;
}
else
{
lblDisplay.Text = "Disconnected";
MessageBox.Show("Error!");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
try
{
serialPort.Close();
lblDisplay.Text = "Disconnected";
lblDisplay.ForeColor = System.Drawing.Color.Green;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
ushort[] holding_register = Master.ReadHoldingRegisters(1, 0, 10);
txtV_Grid.Text = Convert.ToString(holding_register[0]);
txtC_Grid.Text = Convert.ToString(holding_register[1]);
txtP_Grid.Text = Convert.ToString(holding_register[2]);
}
}
private void btnStart_Click(object sender, EventArgs e)
{
if (txtV_Grid.Text.Length > 0 || txtC_Grid.Text.Length > 0 || txtP_Grid.Text.Length > 0)
{
if (truyendata != null || truyendata1 != null)
{
truyendata(txtV_Grid.Text);
truyendata1(txtC_Grid.Text);
truyendata2(txtP_Grid.Text);
}
this.Hide();
}
}
private void txtV_Grid_TextChanged(object sender, EventArgs e)
{
if (truyendata != null)
{
truyendata(txtV_Grid.Text);
}
}
private void txtC_Grid_TextChanged(object sender, EventArgs e)
{
if (truyendata1 != null)
{
truyendata1(txtC_Grid.Text);
}
}
private void txtP_Grid_TextChanged(object sender, EventArgs e)
{
if (truyendata2 != null)
{
truyendata2(txtP_Grid.Text);
}
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void btnOn_ACB_Grid_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
DialogResult dl = MessageBox.Show("Would you like to turn On ACB_GRID", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dl == DialogResult.Yes)
{
Master.WriteSingleCoil(1, 0, true);
}
else
{
Master.WriteSingleCoil(1, 0, false);
}
}
}
private void btnOff_ACB_Grid_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
DialogResult dl = MessageBox.Show("Would you like to turn Off ACB_GRID", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dl == DialogResult.Yes)
{
Master.WriteSingleCoil(1, 0, false);
}
else
{
Master.WriteSingleCoil(1, 0, true);
}
}
}
}
}
Code Form2:
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 SymbolFactoryDotNet;
namespace ATS
{
public partial class frMain : Form
{
public frMain()
{
InitializeComponent();
}
private void communicationToolStripMenuItem_Click(object sender, EventArgs e)
{
frCommunication frm = new frCommunication();
frm.ShowDialog();
}
private void standardControl1_Load(object sender, EventArgs e)
{
}
private void LoadData(string data)
{
txtV.Text = "";
txtV.Text = data;
}
private void LoadData1(string data1)
{
txtC.Text = "";
txtC.Text = data1;
}
private void LoadData2(string data2)
{
txtP.Text = "";
txtP.Text = data2;
}
private void btnConnect_Click(object sender, EventArgs e)
{
frCommunication frm = new frCommunication();
frm.truyendata = new frCommunication.truyendulieu(LoadData);
frm.truyendata1 = new frCommunication.truyendulieu1(LoadData1);
frm.truyendata2 = new frCommunication.truyendulieu2(LoadData2);
frm.ShowDialog();
}
private void txtV_TextChanged(object sender, EventArgs e)
{
}
private void btnStart_Click(object sender, EventArgs e)
{
if(picOn.Visible == false)
{
picOn.Visible = true;
picOff_Grid.Visible = false;
// standardControl3.DiscreteValue2 = true;
}
else
{
picOn.Visible = false;
picOff_Grid.Visible = true;
}
}
private void frMain_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString("HH:mm:ss dd-MM-yyyy");
}
private void btnOn_Grid_Click(object sender, EventArgs e)
{
}
}
}
When I understand you right, you will in Form1 open a connection, close the Form, open a new Form2 and use this connection there?
Well, when that's the case, you could make an special Connection Singleton to hold this connection then you can use it in your Form2
using System;
namespace Sandbox
{
public sealed class Connection
{
private static readonly Lazy<Connection> _instance = new Lazy<Connection>(() => new Connection());
public static Connection Instance => _instance.Value;
private Connection()
{ }
// Implement your Connection Code here.
}
}

Tcp client Server C#

I work on tcp client and server application. I have found in youtube this code. There are no have problem connection with tcp client and server, when i send to message it repeat infinity messagebox like you:you:you:you:.How can i fix this problem? The codes uses backgroundWorker ,it can cause repeat message. Can i solve the problem using Thread class ?
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.Net;
using System.Net.Sockets;
using System.IO;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string recieve;
public String TextToSend;
public Form1()
{
InitializeComponent();
IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress address in localIP)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
textBoxServerIP.Text = address.ToString();
}
}
}
private void buttonStart_Click(object sender, EventArgs e)
{
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBoxServerPort.Text));
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker2.WorkerSupportsCancellation = true;
}
private void buttonConnect_Click(object sender, EventArgs e)
{
client = new TcpClient();
IPEndPoint IpEnd = new IPEndPoint(IPAddress.Parse(textBoxClientIP.Text), int.Parse(textBoxClientPort.Text));
try
{
client.Connect(IpEnd);
if (client.Connected)
{
textBoxChatScreen.AppendText("Connected to server" + "\n");
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker2.WorkerSupportsCancellation = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (client.Connected)
{
try
{
recieve = STR.ReadLine();
this.textBoxChatScreen.Invoke(new MethodInvoker(delegate ()
{
textBoxChatScreen.AppendText("You:" + recieve + "\n");
}));
recieve = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
if (client.Connected)
{
STW.WriteLine (TextToSend);
this.textBoxChatScreen.Invoke(new MethodInvoker(delegate ()
{
textBoxChatScreen.AppendText("Me:" + TextToSend + "\n");
}));
}
else
{
MessageBox.Show("Sending failed");
}
backgroundWorker2.CancelAsync();
}
private void buttonSend_Click(object sender, EventArgs e)
{
if (textBoxMessage.Text != "")
{
TextToSend = textBoxMessage.Text;
backgroundWorker2.RunWorkerAsync();
}
textBoxMessage.Text = "";
}
}
}
I tried the code I can't run from the youtube video below.
https://www.youtube.com/watch?v=X16IyNbcAr0

Transferring from one form to another

So I'm trying to find out and breaking each method while running my codes, and I still can't find why setTempID is always 0, I already assigned a value to it.
Here is 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.Data.Sql;
using System.Data.SqlClient;
//imports
using DHELTASSys.DataAccess;
using DHELTASSys.Modules;
using DHELTASSys.AuditTrail;
namespace Enrollment
{
public partial class HRLogin : Form
{
HRModuleBL obj = new HRModuleBL();
DHELTASSysAuditTrail audit = new DHELTASSysAuditTrail();
public HRLogin()
{
InitializeComponent();
}
private void txtLogin_Click(object sender, EventArgs e)
{
obj.Emp_id = int.Parse(txtEmpID.Text);
audit.Emp_id = int.Parse(txtEmpID.Text);
obj.Password = txtPassword.Text;
if (obj.AccountEnrollmentLogin().Rows.Count == 0)
{
MessageBox.Show("Username and Password is incorrect!");
}
else if (obj.CheckIfHRManager().Rows.Count == 0)
{
MessageBox.Show("You are not allowed to access this system!");
}
else
{
CreateAccount frm = new CreateAccount();
frm.FormClosed += new FormClosedEventHandler(frm_FormClosed);
audit.AddAuditTrail("Has logged in into the Fingerprint Enrollment System.");
frm.setEmpID = int.Parse(txtEmpID.Text);
frm.Show();
this.Hide();
}
}
void frm_FormClosed(object sender, FormClosedEventArgs e)
{
this.Show();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
and here is the other form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
//imports
using DHELTASSys.AuditTrail;
using DHELTASSys.Modules;
namespace Enrollment
{
delegate void Function(); // a simple delegate for marshalling calls from event handlers to the GUI thread
public partial class CreateAccount : Form
{
HRModuleBL obj = new HRModuleBL();
DHELTASSysAuditTrail audit = new DHELTASSysAuditTrail();
private int emp_id;
public int setEmpID
{
set { emp_id = value;}
}
public CreateAccount()
{
InitializeComponent();
}
private void CloseButton_Click(object sender, EventArgs e)
{
Close();
}
private void OnTemplate(DPFP.Template template)
{
this.Invoke(new Function(delegate()
{
Template = template;
VerifyButton.Enabled = SaveButton.Enabled = (Template != null);
if (Template != null)
MessageBox.Show("The fingerprint template is ready for verification and saving", "Fingerprint Enrollment");
else
MessageBox.Show("The fingerprint template is not valid. Repeat fingerprint enrollment.", "Fingerprint Enrollment");
}));
}
private DPFP.Template Template;
private void EnrollButton_Click(object sender, EventArgs e)
{
EnrollmentForm Enroller = new EnrollmentForm();
Enroller.OnTemplate += this.OnTemplate;
Enroller.ShowDialog();
}
private void SaveButton_Click(object sender, EventArgs e)
{
obj.Last_name = txtLastname.Text;
obj.First_name = txtFirstName.Text;
obj.Middle_name = txtMiddleName.Text;
obj.Position_name = cmbPosition.Text;
obj.Company_name = cmbCompany.Text;
obj.Password = txtTempPassword.Text;
obj.Department_name = cmbDepartment.Text;
if (obj.Last_name == string.Empty) //Validation for empty texts
{
MessageBox.Show("Last name can't be empty!");
} else if (obj.First_name == string.Empty)
{
MessageBox.Show("First name can't be empty!");
}
else if (obj.Middle_name == string.Empty)
{
MessageBox.Show("Middle name can't be empty!");
}
else if (obj.Position_name == string.Empty)
{
MessageBox.Show("Position name can't be empty!");
}
else if (obj.Department_name == string.Empty)
{
MessageBox.Show("Deparment can't be empty!");
}
else if (obj.Company_name == string.Empty)
{
MessageBox.Show("Company name can't be empty!");
}
else if (obj.Password == string.Empty)
{
MessageBox.Show("Password can't be empty!");
}
else if (txtConfirmTempPassword.Text == string.Empty)
{
MessageBox.Show("Please verify your input password!");
}
else
{
if (txtTempPassword.Text != txtConfirmTempPassword.Text)
{
MessageBox.Show("Password does not match", "Password Mismatch",
MessageBoxButtons.OK);
}
else
{
MemoryStream fingerprintData = new MemoryStream();
Template.Serialize(fingerprintData);
fingerprintData.Position = 0;
BinaryReader br = new BinaryReader(fingerprintData);
Byte[] bytes = br.ReadBytes((Int32)fingerprintData.Length);
audit.Emp_id = emp_id;
obj.Biometric_code = bytes;
obj.AddAccountSetTempPassword();
}
}
}
private void VerifyButton_Click(object sender, EventArgs e)
{
VerificationForm Verifier = new VerificationForm();
Verifier.Verify(Template);
}
}
}
I'm setting it to frm.setEmpID so that I could get it from another form.
Thanks for the help man.
Perhaps in your SaveButton_Click event in the CreateAccount form you need to set also the Emp_Id variable of the obj instance defined inside that form (as you have done in the instance of the HRModuleBL defined in the first form).
private void SaveButton_Click(object sender, EventArgs e)
{
.....
audit.Emp_id = emp_id;
obj.Emp_id = emp_id;
obj.Biometric_code = bytes;
obj.AddAccountSetTempPassword();
.....
}

UIRobot controller and program in C#

I have this a controller from UIRobot. Here is manual: enter link description here
I want to write software to controle it in C#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace hhh
{
class Program
{
static void Main(string[] args)
{
string ot = "Port je otvoreny";
string za = "Port je zavrety";
string COM = "COM1";
string command = "ENABLE";
SerialPort sp = new SerialPort(COM, 9600);
sp.Open();
if (sp.IsOpen)
{
Console.WriteLine(ot);
sp.Write(command);
sp.ReadLine();
}
else
{
sp.Write(za);
}
Console.ReadKey();
}
}
}
In manual is command ENABLE to initialize controller but it does not work in my code. How Can I send command or where I do a mistake?
I have learned something new so here is update my code and new question.
I want to recieve position of motor. There is command "POS;" which has to give me the value but I get message box with question mark (?) instead number value. Why?
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 System.IO.Ports;
namespace UIRFocuser
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
enable.Enabled = true;
disable.Enabled = false;
zero.Enabled = false;
increase.Enabled = false;
inc10.Enabled = false;
decrease.Enabled = false;
dec10.Enabled = false;
fbk.Enabled = false;
}
private void enable_Click(object sender, EventArgs e)
{
sp.PortName = "COM1";
sp.BaudRate = 9600;
int max = -7000; //max position motor
int min = 0; //min positio of motor
sp.Open();
if (sp.IsOpen)
{
enable.Enabled = false;
disable.Enabled = true;
zero.Enabled = true;
increase.Enabled = true;
inc10.Enabled = true;
decrease.Enabled = true;
dec10.Enabled = true;
fbk.Enabled = true;
sp.Write("ENABLE;");
}
}
private void disable_Click(object sender, EventArgs e)
{
if (sp.IsOpen)
{
sp.Write("OFFLINE;");
sp.Close();
enable.Enabled = true;
disable.Enabled = false;
zero.Enabled = false;
increase.Enabled = false;
inc10.Enabled = false;
decrease.Enabled = false;
dec10.Enabled = false;
fbk.Enabled = false;
}
}
private void zero_Click(object sender, EventArgs e)
{
sp.Write("POS0; SPD400;");
}
private void increase_Click(object sender, EventArgs e)
{
sp.Write("STP1000; SPD400;");
}
private void inc10_Click(object sender, EventArgs e)
{
sp.Write("STP10; SPD400;");
}
private void decrease_Click(object sender, EventArgs e)
{
sp.Write("STP-1000; SPD400;");
}
private void dec10_Click(object sender, EventArgs e)
{
sp.Write("STP10; SPD400;");
}
private void close_Click(object sender, EventArgs e)
{
if (sp.IsOpen)
{
sp.Write("OFFLINE;");
sp.Close();
}
Application.Exit();
}
private void fbk_Click(object sender, EventArgs e)
{
sp.Write("POS;");
string msg = sp.ReadExisting();
MessageBox.Show(msg);
}
}
}
According to that document, the command is "ENABLE;" You have to include the semicolon. So change your code to:
string command = "ENABLE;";

Categories