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);
}
}
}
}
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 having trouble with using serialPort1 in both of my forms. I have opened the serialPort but it just isn't receiving or sending anything. Am I not able to do it this way or is there a simpler way of doing this. Please let me know.
Form 1 Code
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 Arduino_GUI
{
public partial class Form1 : Form
{
public delegate void d1(string indata);
public Form1()
{
InitializeComponent();
serialPort1.Open();
}
private void onButton_Click(object sender, EventArgs e)
{
serialPort1.Write("A"); // on
}
private void offButton_Click(object sender, EventArgs e)
{
serialPort1.Write("a"); // off
}
private void btnOForm2_Click(object sender, EventArgs e)
{
serialPort1.Close();
Form2 f2 = new Form2();
f2.Show();
this.Hide();
}
}
}
Form 2 Code
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 Arduino_GUI
{
public partial class Form2 : Form
{
public delegate void d1(string indata);
public Form2()
{
InitializeComponent();
serialPort1.Open();
}
private void btnMain_Click(object sender, EventArgs e)
{
serialPort1.Close();
Form1 f1 = new Form1();
f1.Show();
this.Hide();
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.WriteLine("2");
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) // receiving data
{
String indata = serialPort1.ReadLine();
d1 writeit = new d1(Write2Form);
Invoke(writeit, indata);
}
public void Write2Form(string indata)
{
char firstchar;
string test;
firstchar = indata[0];
switch (firstchar)
{
case 'r':
test = indata.Substring(1);
label1.Text = test;
break;
}
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
Form1 f1 = new Form1();
f1.Show();
f1.Close();
}
}
}
Arduino Code
String data;
char d1;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available()){
data = Serial.readString();
d1 = data.charAt(0);
switch(d1){ // select action based on first character
case '2': // Do when Form2 opens
Serial.println('r');
break;
}
}
}
Thank you for going through this all and I hope you can help me.
:)
I'm not very versed in coding, let's say this is some kind of project I started without knowing anything about coding.
I have a Button which should read the selection in the comboBox and then open a specific form.
I've tried using following the switch (comboBox1.SelectedText)
While that didn't quite work, I tried another approach:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace The_Liberion_Magnicite
{
public partial class Form1 : The_Liberion_Magnicite.Character
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
comboBox1.SelectedText.ToString();
{ if (comboBox1.SelectedText.ToString() == "Shiroichi Kazami (PTS)")
{
this.Hide();
Shiro1 CShiro1 = new Shiro1();
CShiro1.Show();
}
else if (comboBox1.SelectedText.ToString() == "Shiroichi Kazami (ATS)")
{
this.Hide();
Shiro2 CShiro2 = new Shiro2();
CShiro2.Show();
}
else if (comboBox1.SelectedText.ToString() == "Akari Hondo")
{
this.Hide();
AkariHondo CAkari = new AkariHondo();
CAkari.Show();
}
else if (comboBox1.SelectedText.ToString() == "Aboa Sekihara")
{
this.Hide();
AobaSeki CAoba = new AobaSeki();
CAoba.Show();
}
}
}
}
}
I'm in some dire need for help ;)
I cannot get the ui thread to update the ui while the file copy thread is running. My end goal is to have the animation continue to rotate until the large file copy finally completes to let the user know that the program is not frozen. It's a very simple server to server file copy program.
Can someone tell me what I'm doing wrong?
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;
using System.IO;
using System.Threading.Tasks;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ResetProgress()
{
lblStep1.Image = null;
}
private void SetupProgress()
{
lblStep1.Image = global::animation1.Properties.Resources.animation;
}
private void fileCopy()
{
File.Copy("large file source", "large file destination", true);
}
private void Form1_Load(object sender, EventArgs e)
{
lblStep1.Image = global::animation1.Properties.Resources.animation;
}
private async void button1_Click(object sender, EventArgs e)
{
SetupProgress();
await Task.Run(() => fileCopy());
ResetProgress();
}
private void btnStop_Click(object sender, EventArgs e)
{
// unhandled currently
}
}
}
* Original version *
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;
using System.IO;
using System.Threading.Tasks;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Thread workItemsProducerThread;
private Thread workItemsCopyThread;
public Form1()
{
InitializeComponent();
}
private void ResetProgress()
{
lblStep1.Image = null;
}
private void SetupProgress()
{
this.BeginInvoke((MethodInvoker)delegate ()
{
lblStep1.Image = global::animation1.Properties.Resources.animation;
});
}
private void fileCopy()
{
File.Copy("Large file source", "Large file destination", true);
this.BeginInvoke((MethodInvoker)delegate ()
{
MessageBox.Show("Done");
});
}
private void Form1_Load(object sender, EventArgs e)
{
lblStep1.Image = global::animation1.Properties.Resources.animation;
}
private void btnStart_Click(object sender, EventArgs e)
{
this.workItemsProducerThread = new Thread(new ThreadStart(this.SetupProgress));
this.workItemsProducerThread.IsBackground = true;
this.workItemsProducerThread.Start();
this.SetupProgress();
this.workItemsCopyThread = new Thread(new ThreadStart(this.fileCopy));
this.workItemsCopyThread.IsBackground = true;
this.workItemsCopyThread.Start();
while (workItemsCopyThread.IsAlive)
{
Thread.Sleep(1000); // wait
}
MessageBox.Show("Done");
}
private void btnStop_Click(object sender, EventArgs e)
{
if (this.workItemsProducerThread != null)
{
this.workItemsProducerThread.Abort();
lblStep1.Image = global::animation1.Properties.Resources.animation;
}
}
private void btnTest_Click(object sender, EventArgs e)
{
fileCopy();
}
}
}
Don’t sleep in your click handler. That freezes the UI thread. Just let the clock handler exit. In your file copy thread, when the copy is don’t. Use Invoke(or BeginInvoke) to cause the done messagebox to pop up on the UI thread.
Try this oldy style
private void SetupProgress()
{
Invoke((MethodInvoker) delegate
{
lblStep1.Image = global::animation1.Properties.Resources.animation;
});
}
private Thread TDoSomeWork()
{
var t = new Thread(() => DoSomeWork());
t.Start();
return t;
}
TDoSomeWork();
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();
}