in my current project ,i have a form which contains 2 command buttons named COPY and Cancel
if i click COPY button it is copying 3000 files from source directory to a destination directory ,at the same time if click the Cancel Button , it should cancel the copy and exit the form. is there any way to do so?
i applied the solution but got errors. i have 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.Threading;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
private volatile bool _continue = false;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
_continue = true;
System.Threading.ThreadStart ts = new ThreadStart(print_number);
System.Threading.Thread t = new Thread(ts);
t.Start();
}
private void print_number()
{
for (int i = 1; i <= 10000; i++)
{
textBox1.Text = Convert.ToString(i);
if (_continue == false)
{
return;
}
//Thread.Sleep(2000);
}
}
private void button2_Click(object sender, EventArgs e)
{
_continue = false;
Close();
}
}
}
Example:
private volatile bool _continue = false;
private void CopyClicked(Object sender, EventArgs e)
{
_continue = true;
System.Threading.ThreadStart ts = new ThreadStart(CopyFiles);
System.Threading.Thread t = new Thread(ts);
t.Start();
}
private void CopyFiles(){
List<String> list = GetFileNames();
foreach( String f in list )
{
if ( _continue == false )
{
return;
}
CopyFile(s); //examples...
}
}
private void CancelClicked(Object sender, EventArgs e)
{
_continue = false;
Close();
}
Related
I am trying to write a code for taking fps at label while taking view from the camera.
So, I used task for that and I used timer but I got an error. I fixed the problem with using CheckForIllegalCrossThreadCalls = false; but as far as I know it is not an effective way.
I want to fix this with using invoke. How should I write the code properly?
Here is the code:
using System;
using System.Drawing;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace projectimg
{
public partial class Form1 : Form
{
Stopwatch watch = new Stopwatch();
System.Timers.Timer timerFPS;
public Form1()
{
InitializeComponent();
}
CameraConnection connnection;
private bool btn_GetviewWasClicked = false;
private void Form1_Load(object sender, EventArgs e)
{
btn_Getview.Click += Btn_Getview_Click;
timerFPS = new System.Timers.Timer(1000);
timerFPS.Elapsed += TimerFPS_Elapsed;
timerFPS.Start();
}
private void Btn_Getview_Click(object sender, EventArgs e)
{
btn_GetviewWasClicked = true;
Task.Run(() =>
{
connnection = new CameraConnection();
connnection.Connect();
});
CameraConnection.DataReceived += CameraConnection_DataReceived;
}
private void TimerFPS_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
txt_fps.Text = Convert.ToString(CameraConnection.count);
CameraConnection.count = 0;
}
}
}
I am facing a problem in my winforms app I am building in Visual Studio 2019. My app has 8 forms and I constructed a new class in which I want to save the name of the forms that users visited through a list and save them in a .txt file. I am providing you the pieces of code that I am trying to implement.
Code of one of 8 forms
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Delfoi_Tourist_Guide
{
public partial class Welcome : Form
{
SQLiteConnection connection;
private SpeechSynthesizer speech = new SpeechSynthesizer();
public Welcome()
{
InitializeComponent();
User_History.HistList.Add(this.Name);
User_History.SaveHistory();
}
private void Welcome_Load(object sender, EventArgs e)
{
String conn = "Data Source=Delfoidb1.db;Version=3";
connection = new SQLiteConnection(conn);
connection.Open(); //or Create Database
}
private void Timer1_Tick(object sender, EventArgs e)
{
label1.Show();
label2.Show();
button1.Visible = true;
button2.Visible = true;
timer2.Enabled = true;
timer1.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
if (speech.State == SynthesizerState.Speaking)
{
speech.Pause();
}
Form2 form2 = new Form2();
form2.Show();
this.Visible = false;
}
private void button6_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void timer2_Tick(object sender, EventArgs e)
{
speech.SelectVoice("Microsoft Stefanos");
speech.SpeakAsync(label2.Text);
timer2.Enabled = false;
}
private void button2_Click(object sender, EventArgs e)
{
if (speech.State == SynthesizerState.Speaking)
{
speech.Pause();
}
Form8 form8 = new Form8();
form8.Show();
this.Visible = false;
}
private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
{
MessageBox.Show("Developed by Ανδρέας Κρεούζος(ΜΠΠΛ20040) and Δημήτρης Γιογάκης(ΜΠΠΛ20008)");
}
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
//Implement try - catch to avoid exception specifically for url error
try
{
Help.ShowHelp(this, "_tmphhp/Delfoi_Tourist_Guide_Help.chm", HelpNavigator.KeywordIndex, "Topic 1");
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
}
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
if (speech.State == SynthesizerState.Speaking)
{
speech.Pause();
}
Welcome welcome = new Welcome();
welcome.Show();
this.Visible = false;
}
private void έξοδοςToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
Code of the separate class that saves the data as txt
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Delfoi_Tourist_Guide
{
public static class User_History
{
public static List<string> HistList = new List<string>();
public static void SaveHistory()
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string path = saveFileDialog.FileName;
StreamWriter sw = new StreamWriter(path);
sw.WriteLine(HistList);
sw.Close();
}
}
}
}
My problem is that I can't transfer the data (placed on the InitializeComponent) from forms to my class. I am getting my txt file with nothing in it. My data is actually saved on my public static list but I can't transfer it next to the rest of my User_History class.
Any ideas on how to accomplish this???
You can try this SaveHistory() method
public static void SaveHistory()
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string path = saveFileDialog.FileName;
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (string history in HistList)
{
writer.WriteLine(history);
}
}
}
}
This question already has answers here:
How do you pass an object from form1 to form2 and back to form1?
(4 answers)
Closed 5 years ago.
I'm supposed to make a math practice program for kids. They should be able to choose 1 operation and the amount of digits (1, 2 or 3 digit) the numbers will have. It then has to out put 10 random questions according to the selection made by the kid, then once they have completed the quiz, it should display their results and which questions they got wrong.
I have two selections being made on form1, operations and # of digits, which are assigned numbers (1. (*) 2. (/) 3. (+) 4. (-)). All i need to do is communicate the operation number and # of digits to form2, where the questions will be generated and displayed.
Here's my code for form1 so far:
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 FinalProject
{
public partial class Form1 : Form
{
public static int operation = 0;
public static int digits = 0;
public Form1()
{
InitializeComponent();
}
// this is to make sure only one box is checked for both selections. Starts here
private void label1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
}
private void MulCB_CheckedChanged(object sender, EventArgs e)
{
if ( MulCB.Checked == true)
{
operation = 1;
DivCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void DivCB_CheckedChanged(object sender, EventArgs e)
{
if (DivCB.Checked == true)
{
operation = 2;
MulCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void AddCB_CheckedChanged(object sender, EventArgs e)
{
if (AddCB.Checked == true)
{
operation = 3;
DivCB.Checked = false;
SubCB.Checked = false;
MulCB.Checked = false;
}
}
private void SubCB_CheckedChanged(object sender, EventArgs e)
{
if (SubCB.Checked == true)
{
operation = 4;
DivCB.Checked = false;
AddCB.Checked = false;
MulCB.Checked = false;
}
}
private void oneDCB_CheckedChanged(object sender, EventArgs e)
{
if(oneDCB.Checked == true)
{
digits = 1;
twoDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void twoDCB_CheckedChanged(object sender, EventArgs e)
{
if ( twoDCB.Checked == true)
{
digits = 2;
oneDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void threeDCB_CheckedChanged(object sender, EventArgs e)
{
if (threeDCB.Checked == true)
{
digits = 3;
oneDCB.Checked = false;
twoDCB.Checked = false;
}
}
private void button8_Click(object sender, EventArgs e)
{
// operations: 1. (*) 2. (/) 3. (+) 4. (-)
// digits are as number indicates.
// Second window popup.
Form2 settingsForm = new Form2();
settingsForm.Show();
}
}
}
Here's form2, naked pretty much.
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 FinalProject
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void FinishedBtn_Click(object sender, EventArgs e)
{
}
}
}
This might work.
There are comments in the code.
The workflow is creating a new instance of the class Form2 and setting two public variables. Public means that they can be accessed from outside of the class (see here, if you want). Then the method Show() is called and the Form appears. In the Form2 code, the public variables now have the values previously specified and can be used.
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;
namespace FinalProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// this is to make sure only one box is checked for both selections. Starts here
private void label1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
}
private void MulCB_CheckedChanged(object sender, EventArgs e)
{
if ( MulCB.Checked == true)
{
operation = 1;
DivCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void DivCB_CheckedChanged(object sender, EventArgs e)
{
if (DivCB.Checked == true)
{
operation = 2;
MulCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void AddCB_CheckedChanged(object sender, EventArgs e)
{
if (AddCB.Checked == true)
{
operation = 3;
DivCB.Checked = false;
SubCB.Checked = false;
MulCB.Checked = false;
}
}
private void SubCB_CheckedChanged(object sender, EventArgs e)
{
if (SubCB.Checked == true)
{
operation = 4;
DivCB.Checked = false;
AddCB.Checked = false;
MulCB.Checked = false;
}
}
private void oneDCB_CheckedChanged(object sender, EventArgs e)
{
if(oneDCB.Checked == true)
{
digits = 1;
twoDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void twoDCB_CheckedChanged(object sender, EventArgs e)
{
if ( twoDCB.Checked == true)
{
digits = 2;
oneDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void threeDCB_CheckedChanged(object sender, EventArgs e)
{
if (threeDCB.Checked == true)
{
digits = 3;
oneDCB.Checked = false;
twoDCB.Checked = false;
}
}
private void button8_Click(object sender, EventArgs e)
{
// operations: 1. (*) 2. (/) 3. (+) 4. (-)
// digits are as number indicates.
// Second window popup.
// it's the question form, right?
Form2 questionForm = new Form2();
//"Write" your settings in the other form's variables
//You will have to write code that finds out which checkbox is which number! For now its fixed.
questionForm.operation = 2;
questionForm.digits = 1;
questionForm.Show();
//Hide Form1
this.Hide();
}
}
}
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;
namespace FinalProject
{
public partial class Form2 : Form
{
public static int operation;
public static int digits;
public Form2()
{
InitializeComponent();
}
//do NOT paste this. It can be added by creating an event handler
// you also might not need this, but this method is called when this Form appears. It's an example.
// https://msdn.microsoft.com/en-us/library/zwwsdtbk(v=vs.80).aspx
private void Form2_Load(object sender, EventArgs e)
{
//here you can use your variables for example (also anywhere within this class!)
//e.g.
Textbox1.Text = (string)operation;
}
private void FinishedBtn_Click(object sender, EventArgs e)
{
}
}
}
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;";
This one is giving me a hard time.
The thing is that I have a code that plays some notes in MIDI, and I wanted to be able to pause it, so I made a simple Form like this:
namespace Music
{
public partial class Form1 : Form
{
static BackgroundWorker _bw = new BackgroundWorker
{
WorkerSupportsCancellation = true
};
private void button1_Click(object sender, EventArgs e)
{
if (!Playing)
{
Playing = true;
_bw.DoWork += Start_Playing;
_bw.RunWorkerAsync("Hello to worker");
}
else
{
Playing = false;
_bw.CancelAsync();
}
}
static void Start_Playing(object sender, DoWorkEventArgs e)
{
//Plays some music
}
}
}
And when I click it starts playing, but no matter what I do, it can't stop. But the thing is that if I do the same thing in the console it works perfect.
Did I miss something?
How can I control a separate thread from the form?
This seems to work...
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.Threading;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private BackgroundWorker _bw = new BackgroundWorker { WorkerSupportsCancellation = true,
WorkerReportsProgress = true};
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (_bw.IsBusy)
{
_bw.CancelAsync();
}
else
{
_bw.ProgressChanged += new ProgressChangedEventHandler(_bw_ProgressChanged);
_bw.DoWork += new DoWorkEventHandler(_bw_DoWork);
_bw.RunWorkerAsync();
}
}
void _bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
textBox1.Text += (string)e.UserState;
}
void _bw_DoWork(object sender, DoWorkEventArgs e)
{
int count = 0;
while (!_bw.CancellationPending)
{
_bw.ReportProgress(0, string.Format("worker working {0}", count));
++count;
Thread.Sleep(2000);
}
}
}
}