In Microsoft Visual Studio, I have Form1.cs, which contains several buttons such as btnHome, etc. When one of them is clicked (in this case btnHome), it opens the child form FormHome.cs. When the Start button is clicked in FormHome.cs, a process starts that runs every 10 seconds and does not stop until the stop or pause button is clicked. However, if I click on the btnStatus or btnSettings button from the menu bar and return to the btnHome button, the process already stopped. What should I do to prevent it from stopping? I know that the data needs to be saved in a database, I'll handle that later, but how can I make the process not stop if navigating between other child forms?
Form1.cs
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;
namespace test
{
public partial class panel : Form
{
private Button currentButton;
private Random random;
private int tempIndex;
private Form activateForm;
public panel()
{
InitializeComponent();
random = new Random();
}
private Color SelectThemeColor()
{
int index = random.Next(ThemeColor.ColorList.Count);
while (tempIndex == index)
{
index = random.Next(ThemeColor.ColorList.Count);
}
tempIndex = index;
string color = ThemeColor.ColorList[index];
return ColorTranslator.FromHtml(color);
}
private void ActivateButton(object btnSender)
{
if (btnSender != null)
{
if (currentButton != (Button)btnSender)
{
DisableButton();
Color color = SelectThemeColor();
currentButton = (Button)btnSender;
currentButton.BackColor = color;
currentButton.ForeColor = Color.White;
currentButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
panelTitleBar.BackColor = color;
}
}
}
private void DisableButton()
{
foreach (Control previousBtn in panelMenu.Controls)
{
if (previousBtn.GetType() == typeof(Button))
{
previousBtn.BackColor = panelMenu.BackColor;
previousBtn.ForeColor = Color.Gainsboro;
previousBtn.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
}
}
}
private void OpenChildForm(Form childForm, object btnSender)
{
ActivateButton(btnSender);
if (activateForm != null)
{
activateForm.Close();
}
activateForm = childForm;
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
childForm.Dock = DockStyle.Fill;
this.panelDesktopPane.Controls.Add(childForm);
this.panelDesktopPane.Tag = childForm;
childForm.BringToFront();
childForm.Show();
lblTitle.Text = childForm.Text;
}
private void btnHome_Click(object sender, EventArgs e)
{
OpenChildForm(new Forms.FormHome(), sender);
}
private void btnStatus_Click(object sender, EventArgs e)
{
OpenChildForm(new Forms.FormStatus(), sender);
}
private void btnSettings_Click(object sender, EventArgs e)
{
OpenChildForm(new Forms.FormSettings(), sender);
}
}
}
FormHome.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
namespace test.Forms
{
public partial class FormHome : Form
{
private static readonly string IPv4Pattern = #"^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
private System.Windows.Forms.Timer _timer;
public FormHome()
{
InitializeComponent();
homePanel2ListView1CurlResults.View = View.Details;
homePanel2ListView1CurlResults.Columns.Add("Time");
homePanel2ListView1CurlResults.Columns.Add("Result");
}
private void homePanel1Button2Start_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(homePanel1TextBox1PublicIP.Text))
{
MessageBox.Show("Please enter a IPv4 address.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!System.Text.RegularExpressions.Regex.IsMatch(homePanel1TextBox1PublicIP.Text, IPv4Pattern))
{
MessageBox.Show("Please enter a valid IPv4 address.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
string selectedTime = homePanel1ComboBox1Time.SelectedItem?.ToString();
if (selectedTime == null)
{
MessageBox.Show("Please select a time.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
int interval = 10000;
_timer = new System.Windows.Forms.Timer
{
Interval = interval
};
_timer.Tick += new EventHandler(TimerTick);
_timer.Start();
}
private void homePanel1Button3Pause_Click(object sender, EventArgs e)
{
_timer.Stop();
}
private void homePanel1Button4Stop_Click(object sender, EventArgs e)
{
_timer.Stop();
homePanel2ListView1CurlResults.Items.Clear();
}
private void TimerTick(object sender, EventArgs e)
{
var result = GetPublicIP();
homePanel2ListView1CurlResults.Items.Add(new ListViewItem(new[] { DateTime.Now.ToString("HH:mm:ss"), result }));
}
private string GetPublicIP()
{
try
{
using (WebClient client = new WebClient())
{
string response = client.DownloadString("http://ifconfig.me");
return response;
}
}
catch (Exception ex)
{
MessageBox.Show("Error retrieving IP address: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return string.Empty;
}
}
}
}
The problem here is scope.
This isn't working because your timer is defined on FormHome and is destroyed when you navigate out of scope.
You could try passing your timer object as a parameter to other form when you navigate or try using an async task.
I would try something like this.
Form1.cs
private bool timerIsRunning;
...
private void btnHome_Click(object sender, EventArgs e)
{
OpenChildForm(new Forms.FormHome(timerIsRunning), sender);
}
FormHome.cs
bool timerIsRunning;
public FormHome(bool _timerIsRunning)
{
...
timerisRunning = _timerIsRunning;
}
private void homePanel1Button2Start_Click(object sender, EventArgs e)
{
timerIsRunning = true;
StartTimer();
}
private void homePanel1Button4Stop_Click(object sender, EventArgs e)
{
timerIsRunning = false;
}
async void StartTimer ()
{
while (timerIsRunning)
{
await Task.Delay(10000);
TimerTick();
}
}
private void TimerTick()
{
// Event code here
}
Related
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.
}
}
I'm trying to realize web searches to get the title of websites on a Google search.
I got a code that works well on other sites, but using Google I got duplicated results.
I have tried and tried, but I can't see where is the mistake.
Code simplified:
public partial class Form1 : Form
{
WebBrowser navegador = new WebBrowser();
private void Form1_Load(object sender, EventArgs e)
{
navegador.ScriptErrorsSuppressed = true;
navegador.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(this.datos);
}
private void datos(object sender, EventArgs e)
{
try
{
foreach (HtmlElement etiqueta in navegador.Document.All)
{
if (etiqueta.GetAttribute("classname").Contains("LC20lb DKV0Md"))
{
listBox1.Items.Add(etiqueta.InnerText);
}
}
}
catch (Exception exception) { }
}
private void function(object sender, EventArgs e)
{
/// string query = "https://google.com/search?q=" + query_box.Text;
navegador.Navigate("https://google.com/search?q=water");
/// this.Text = query;
}
}
Result:
I don't know how google works but you can prevent duplicates like this
if(!listBox1.Items.Contains(etiqueta.InnerText))
listBox1.Items.Add(etiqueta.InnerText);
After a couple of days researching and improving the code I decided to change the list for a table.
In addition, now the searches are not duplicated and are positioned in the table as expected
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;
namespace SourceDownloader
{
public partial class Form1 : Form
{
strs valor = new strs();
public Form1()
{
InitializeComponent();
}
WebBrowser navegador = new WebBrowser();
private void Form1_Load(object sender, EventArgs e)
{
navegador.ScriptErrorsSuppressed = true;
navegador.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(this.datos);
}
private void datos(object sender, EventArgs e)
{
try
{
foreach (HtmlElement etq in navegador.Document.All)
{
if (etq.GetAttribute("classname").Contains("r")) /// LC20lb DKV0Md
{
foreach (HtmlElement a_et in etq.GetElementsByTagName("a"))
{
valor.link = a_et.GetAttribute("href");
}
foreach (HtmlElement t_et in etq.GetElementsByTagName("h3"))
{
valor.tit = t_et.InnerText;
}
bool exist = dataGridView1.Rows.Cast<DataGridViewRow>().Any(row => Convert.ToString(row.Cells["link"].Value) == valor.link);
var s1 = valor.link;
bool b = s1.Contains("google.com");
bool a = s1.Contains("googleusercontent");
if (!exist /* && !b && !a*/)
{
dataGridView1.Rows.Insert(0, valor.tit, valor.link);
}
}
if (etq.GetAttribute("classname").Contains("G0iuSb"))
{
valor.next = etq.GetAttribute("href");
}
}
more_ops.Enabled = true;
}
catch (Exception)
{
}
}
private void function(object sender, EventArgs e)
{
string query = "https://google.com/search?q=" + query_box.Text;
navegador.Navigate(query);
this.Text = query;
}
private void more_ops_Click(object sender, EventArgs e)
{
string query = valor.next;
navegador.Navigate(query);
this.Text = query;
}
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
try
{
var msg = dataGridView1.CurrentCell.Value;
System.Diagnostics.Process.Start(msg.ToString());
}
catch (Exception)
{
MessageBox.Show("Error");
}
}
private void Enter(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
string texto = query_box.Text;
texto = texto.Replace("\n", "");
query_box.Text = texto;
string query = "https://google.com/search?q=" + query_box.Text;
navegador.Navigate(query);
this.Text = query;
}
}
}
/// global values
class strs
{
private string _link = "N/A";
private string _tit = "N/A";
private string _next = "N/A";
public string tit
{
get
{
return _tit;
}
set
{
_tit = value;
}
}
public string link
{
get
{
return _link;
}
set
{
_link = value;
}
}
public string next
{
get
{
return _next;
}
set
{
_next = value;
}
}
}
}
I am using c# Windows Form Application and ftpWebRequest, I am doing a directory listing. I have a listbox that will display folders, by using the event DoubleClick in my listbox, the double clicked folder or item in my listbox will show its content. And now my problem is I don't know how to go back to the previous directory by using back button.
Here is my Code File:
namespace myFTPClass
{
public class myFTP
{
public string user;
public string pass;
public delegate void cThread1(string thread1);
public event EventHandler EH;
public List<string> myDIR = new List<string>();
public void getDirectoryList(string getDirectory)
{
try
{
FtpWebRequest fwr = FtpWebRequest.Create(getDirectory) as FtpWebRequest;
fwr.Credentials = new NetworkCredential(user, pass);
fwr.UseBinary = true;
fwr.UsePassive = true;
fwr.KeepAlive = true;
fwr.Method = WebRequestMethods.Ftp.ListDirectory;
StreamReader sr = new StreamReader(fwr.GetResponse().GetResponseStream());
while (!sr.EndOfStream)
{
myDIR.Add(sr.ReadLine());
}
}
catch(Exception we)
{
myDIR.Clear();
string msg = we.Message;
}
}
void myCallBackMethod(IAsyncResult ar)
{
cThread1 myThread = (cThread1)((System.Runtime.Remoting.Messaging.AsyncResult)ar).AsyncDelegate;
myThread.EndInvoke(ar);
if (EH != null) EH(this, null);
}
public void Async_getDirectoryList(string dir)
{
AsyncCallback ac = new AsyncCallback(myCallBackMethod);
cThread1 myThread = new cThread1(getDirectoryList);
myThread.BeginInvoke(dir, ac, null);
}
}
}
And Here is my Form1:
namespace my_ftp_v0._01
{
public partial class Form1 : Form
{
myFTP ftp = new myFTP();
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
btn_connect.Click += new EventHandler(btn_connect_Click);
listBox1.DoubleClick += new EventHandler(listBox1_DoubleClick);
btn_back.Click += new EventHandler(btn_back_Click);
ftp.EH += new EventHandler(ftp_EH);
}
void btn_back_Click(object sender, EventArgs e)
{
}
void listBox1_DoubleClick(object sender, EventArgs e)
{
string forward = "ftp://127.0.0.1/" + listBox1.SelectedItem.ToString();
listBox1.Items.Clear();
ftp.myDIR.Clear();
ftp.Async_getDirectoryList(forward);
}
void Form1_Load(object sender, EventArgs e)
{
txt_dir.Text = "ftp://127.0.0.1/";
txt_pass.PasswordChar = '‡';
}
void ftp_EH(object sender, EventArgs e)
{
if (InvokeRequired)
{
EventHandler eh = new EventHandler(ftp_EH);
this.Invoke(eh, new object[] { sender, e });
return;
}
for (int i = 0; i < ftp.myDIR.Count; i++)
{
listBox1.Items.Add(ftp.myDIR[i]);
}
}
void btn_connect_Click(object sender, EventArgs e)
{
ftp.Async_getDirectoryList(txt_dir.Text);
ftp.user = txt_user.Text;
ftp.pass = txt_pass.Text;
}
}
}
Move your SetDirectoryList to its own method
Add a Stack object to your class to track your requests
When the user double clicks add the request to the stack and then set the directory.
When the user hits the back
button, check if the stack has a request, if it does, pop it off and
call the set directory method.
Something like this...
public partial class Form1 : Form
{
myFTP ftp = new myFTP();
Stack _requestStack = new Stack();//Stack to store requests
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
btn_connect.Click += new EventHandler(btn_connect_Click);
listBox1.DoubleClick += new EventHandler(listBox1_DoubleClick);
btn_back.Click += new EventHandler(btn_back_Click);
ftp.EH += new EventHandler(ftp_EH);
}
void btn_back_Click(object sender, EventArgs e)
{
if(_requestStack.Count > 0)
{
string directoryPath = (string)_requestStack.Pop();
SetDirectoryList(directoryPath);
}
}
void listBox1_DoubleClick(object sender, EventArgs e)
{
string directoryPath = listBox1.SelectedItem.ToString();
_stack.Push(directoryPath);
SetDirectoryList(directoryPath);
}
void SetDirectoryList(string directoryPath)
{
string forward = "ftp://127.0.0.1/" + directoryPath;
listBox1.Items.Clear();
ftp.myDIR.Clear();
ftp.Async_getDirectoryList(forward);
}
void btn_back_Click(object sender, EventArgs e)
{
create.server = create.server.TrimEnd('/');
create.server = create.server.Remove(create.server.LastIndexOf('/')+1);
listBox1.Items.Clear();
ftp.myDIR.Clear();
ftp.Async_getDirectoryList("");
}
I've already done this code to my back button and it works properly.
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;";
I am trying to make my listBox (lstFiles) selectable, so it's able to display the image file within a pictureBox (pictureBox1) and change after selecting another file from listBox, Im creating a webcam program that takes pictures which works, but having trouble with with displaying the images.
I have tried many ways but can't get it to work from selecting the filename from the listbox
Any help would be grateful thank you
This is what I have so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Pinvoke;
using System.IO;
namespace TestAvicap32
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitializeDevicesList();
}
private void InitializeDevicesList()
{
splitContainer1.Panel1.Enabled = true;
splitContainer1.Panel2.Enabled = false;
foreach (CaptureDevice device in CaptureDevice.GetDevices())
{
cboDevices.Items.Add(device);
}
if (cboDevices.Items.Count > 0)
{
cboDevices.SelectedIndex = 0;
}
}
private void btnStart_Click(object sender, EventArgs e)
{
int index = cboDevices.SelectedIndex;
if (index != -1)
{
splitContainer1.Panel1.Enabled = false;
splitContainer1.Panel2.Enabled = true;
((CaptureDevice)cboDevices.SelectedItem).Attach(pbImage);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
splitContainer1.Panel1.Enabled = true;
splitContainer1.Panel2.Enabled = false;
((CaptureDevice)cboDevices.SelectedItem).Detach();
}
private void btnSnapshot_Click(object sender, EventArgs e)
{
try
{
Image image = ((CaptureDevice)cboDevices.SelectedItem).Capture();
image.Save(#"c:\webcapture\" + DateTime.Now.ToString("HH.mm.ss-dd-MM-yy") + ".png", ImageFormat.Png);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btntimer_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
btntimerstop.Visible = true;
btntimer.Visible = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
Image image = ((CaptureDevice)cboDevices.SelectedItem).Capture();
image.Save(#"c:\webcapture\" + DateTime.Now.ToString("HH.mm.ss-dd-MM-yy") + ".png", ImageFormat.Png);
}
private void btntimerstop_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
btntimer.Visible = true;
btntimerstop.Visible = false;
}
private void Form1_Load(object sender, EventArgs e)
{
btntimerstop.Visible = false;
foreach (DriveInfo di in DriveInfo.GetDrives())
lstDrive.Items.Add(di);
}
private void lstFolders_SelectedIndexChanged(object sender, EventArgs e)
{
lstFiles.Items.Clear();
DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;
foreach (FileInfo fi in dir.GetFiles())
lstFiles.Items.Add(fi);
}
private void lstDrive_SelectedIndexChanged(object sender, EventArgs e)
{
lstFolders.Items.Clear();
try
{
DriveInfo drive = (DriveInfo)lstDrive.SelectedItem;
foreach (DirectoryInfo dirInfo in drive.RootDirectory.GetDirectories())
lstFolders.Items.Add(dirInfo);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void lstFiles_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
//I don't know If I need this?
}
}
}
Try like below... it will work....
private void lstFiles_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(((FileInfo)lstFiles.SelectedItem).FullName);
}