I am posting a sample code to decode a problem with a larger code.
I have a 2 seconds timer - System.Windows.Forms.Timer
Every 2 seconds i increment a global int by one, and show its value using MessageBox
If the int reaches 4, i turn off the main flag.
Here is the 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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
bool Play_On = false;
int i = 0;
public Form1()
{
InitializeComponent();
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Play")
{
button1.Text = "Puase";
Play_On = true;
}
else
{
button1.Text = "Play";
Play_On = false;
}
}
private void Form1_Load(object sender, EventArgs e)
{
Timer MinResTimer = new Timer();
{
MinResTimer.Tick += new EventHandler(MinResTimer_Elapsed);
MinResTimer.Interval = 2000;
MinResTimer.Enabled = true;
MinResTimer.Start();
}
}
public void MinResTimer_Elapsed(object sender, EventArgs e)
{
if (Play_On == true)
{
MessageBox.Show("timed"+ i.ToString());
i++;
}
if (i == 4)
{
Play_On = false;
button1.Text = "Play";
}
}
}
}
The problem is that the flag isnt being turned off at all.
The output I am getting is Timed0 - In a messagebox, many times.
I think I have some problem with the messagebox - not sure
Could someone help me find out whats going on here?
Move your increment of i++ to before you call MessageBox
Then you will see that you really want to protect the event from still firing while the message box is displayed.
so your new code would move the I++ to before the MessageBox and then you would disable and enable the timer before and after the message box is called.
When the messagebox show,then you didn't click the 'OK' button to close the messagebox, i++ can not do.So i always equals 0 before you click the 'OK' button on messagebox.
void MinResTimer_Elapsed(object sender, EventArgs e)
{
if (Play_On == true)
{
i++;
MessageBox.Show("timed" + i.ToString());
}
if (i == 4)
{
Play_On = false;
MinResTimer.Enabled = false;
button1.Text = "Pause";
}
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Play")
{
button1.Text = "Puase";
MinResTimer.Enabled = true;
i = 0;
Play_On = true;
}
else
{
button1.Text = "Play";
MinResTimer.Enabled = false;
Play_On = false;
}
}
EDIT #1:
bool Play_On = false;
int i = 0;
Timer MinResTimer;
private void Form1_Load(object sender, EventArgs e)
{
MinResTimer = new Timer();
{
MinResTimer.Tick += new EventHandler(MinResTimer_Elapsed);
MinResTimer.Interval = 2000;
MinResTimer.Enabled = true;
MinResTimer.Start();
}
}
void MinResTimer_Elapsed(object sender, EventArgs e)
{
if (Play_On == true && i <= 4)
{
i++;
MessageBox.Show("timed" + i.ToString());
}
if (i == 4)
{
Play_On = false;
button1.Text = "Pause";
}
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Play")
{
button1.Text = "Puase";
Play_On = true;
}
else
{
button1.Text = "Play";
Play_On = false;
}
}
Related
This is a simple calculator program I am trying to make using Windows Forms Application in VS. The UnhandledException appears when I click anywhere except on the calculator buttons. I am fairly new to C# and it seems that a sender button in my function "common_operators" is causing the exception. Also, I want this calculator to have similar memory functionalities as windows 10's built-in calculator. I've searched everywhere but couldn't find a c# calculator implementation that is similar to Win10's built-in calculator has, I have already started but I think there's a better way to implement it. If u need more info, I've uploaded the "designer.cs" file that relates to the form application.
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 WindowsFormsApp_Calculator;
namespace WindowsFormsApp_Calculator
{
public partial class CalculatorBase : Form
{
public double[] arrMemory = new double[5];
public int indexer = 0;
double result = 0;
string asmd_operator = ""; // ASMD - Addition, Subtraction, Multiplication, Division
bool insert_value = false;
public CalculatorBase()
{
InitializeComponent();
btn_mc.Enabled = false;
btn_mr.Enabled = false;
mem_textbox.Text = "There's nothing saved in memory";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void numbers_zerotonine(object sender, EventArgs e)
{
Button b = (Button)sender;
if((box_display.Text == "0") || insert_value)
box_display.Text = "";
insert_value = false;
box_display.Text = box_display.Text + b.Text;
}
private void common_operators(object sender, EventArgs e)
{
Button b = (Button)sender;
if (result != 0)
{
btn_eql.PerformClick();
insert_value = true;
asmd_operator = b.Text;
subbox_display.Text = result + " " + asmd_operator;
}
else
{
asmd_operator = b.Text;
result = double.Parse(box_display.Text);
box_display.Text = "";
subbox_display.Text = System.Convert.ToString(result) + " " + asmd_operator;
}
}
private void btn_ce_Click(object sender, EventArgs e)
{
box_display.Text = "0";
}
private void btn_c_Click(object sender, EventArgs e)
{
box_display.Text = "0";
subbox_display.Text = "";
result = 0;
}
private void btn_eql_Click(object sender, EventArgs e)
{
subbox_display.Text = "";
switch(asmd_operator)
{
case "-":
box_display.Text = (result - double.Parse(box_display.Text)).ToString();
break;
case "+":
box_display.Text = (result + double.Parse(box_display.Text)).ToString();
break;
case "X":
box_display.Text = (result * double.Parse(box_display.Text)).ToString();
break;
case "/":
box_display.Text = (result / double.Parse(box_display.Text)).ToString();
break;
default:
break;
}
result = double.Parse(box_display.Text);
asmd_operator = "";
}
private void btn_bs_Click(object sender, EventArgs e)
{
if(box_display.Text.Length > 0)
{
box_display.Text = box_display.Text.Remove(box_display.Text.Length - 1, 1);
}
if(box_display.Text == "")
{
box_display.Text = "0";
}
}
private void btn_ms_Click(object sender, EventArgs e)
{
if (indexer == 5)
{
mem_textbox.Text = "Memory is full. Max limit = 5";
}
else
{
int hgt = 75;
mem_textbox.Text = "";
arrMemory[indexer] = double.Parse(box_display.Text);
indexer++;
btn_mc.Enabled = true;
btn_mr.Enabled = true;
TextBox mem = new TextBox();
mem.Multiline = true;
mem.TextAlign = HorizontalAlignment.Right;
mem.Width = 275;
mem.Height = 70;
mem.Font = new Font(mem.Font.FontFamily, 20);
mem.Text = box_display.Text;
mem.Location = new Point(387, hgt);
this.Controls.Add(mem);
}
}
private void btn_mc_Click(object sender, EventArgs e)
{
foreach (int i in arrMemory)
{
arrMemory[i] = 0;
}
indexer = 0;
btn_mr.Enabled = false;
btn_mc.Enabled = false;
mem_textbox.Text = "There's nothing saved in memory";
}
private void btn_mr_Click(object sender, EventArgs e)
{
box_display.Text = arrMemory[indexer].ToString();
}
private void btn_mp_Click(object sender, EventArgs e)
{
arrMemory[indexer] += double.Parse(box_display.Text);
}
private void btn_mm_Click(object sender, EventArgs e)
{
arrMemory[indexer] -= double.Parse(box_display.Text);
}
}
}
From your designer.cs you've got a Click event handler on the form itself that invokes common_operators, so if that gets fired, it will be an invalid cast since sender will be your CalculatorBase form type and not Button
How created a simple slideshow with a PictureBox element.
Now I would like to open an image by clicking on it to see it in full resolution - with the default app which is associated with .jpg files (e.g. Microsoft Photos). I think a click event on the PictureBox would be the way to go but I don't know what code to add. Couldn't find a good example on the internet.
Following the code I use so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Diashow
{
public partial class Form1 : Form
{
private string[] folderFile = null;
private int selected = 0;
private int begin = 0;
private int end = 0;
public Form1()
{
InitializeComponent();
this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
folderBrowserDialog1.SelectedPath = #"E:\MiscTest\";
timer1.Interval = 5000;
}
private void btnOpen_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
string[] part1 = null, part2 = null, part3 = null;
part1 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpg");
part2 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpeg");
part3 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.tif");
folderFile = new string[part1.Length + part2.Length + part3.Length];
Array.Copy(part1, 0, folderFile, 0, part1.Length);
Array.Copy(part2, 0, folderFile, part1.Length, part2.Length);
Array.Copy(part3, 0, folderFile, part1.Length + part2.Length, part3.Length);
selected = 0;
begin = 0;
end = folderFile.Length;
showImage(folderFile[selected]);
btnPrevious.Enabled = true;
btnNext.Enabled = true;
bntSlideshow.Enabled = true;
}
}
private void showImage(string path)
{
Image imgtemp = Image.FromFile(path);
pictureBox1.Image = imgtemp;
}
private void btnNext_Click(object sender, EventArgs e)
{
if (selected == folderFile.Length - 1)
{
selected = 0;
showImage(folderFile[selected]);
}
else
{
selected = selected + 1; showImage(folderFile[selected]);
}
}
private void btnPrevious_Click(object sender, EventArgs e)
{
if (selected == 0)
{
selected = folderFile.Length - 1;
showImage(folderFile[selected]);
}
else
{
selected = selected - 1; showImage(folderFile[selected]);
}
}
private void nextImage()
{
if (selected == folderFile.Length - 1)
{
selected = 0;
showImage(folderFile[selected]);
}
else
{
selected = selected + 1; showImage(folderFile[selected]);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (pictureBox1.Image != null)
{
pictureBox1.Image.Dispose();
}
nextImage();
}
private void bntSlideshow_Click(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
timer1.Enabled = false;
bntSlideshow.Text = "START Slideshow";
}
else
{
timer1.Enabled = true;
bntSlideshow.Text = "STOP Slideshow";
}
}
}
}
I am still new at programming, I code as a hobby :)
I wanted to make a MJPEG streaming aplication with an option to record a video and save it on computer when it detects a moving. So far i've managed to get stream to videosourceplayer in WPF, but it seems that i can't manage to get the information whether moving is detected or not. What am i doing wrong? i've tried many things ( commented ). but it seems that i can't compare float MotionDetected to limited (in my case 0.02). my label5 simply doesnt change.
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 AForge.Vision.Motion;
using AForge.Video;
using AForge.Video.DirectShow;
using Accord.Video.FFMPEG;
using System.Globalization;
using AForge.Controls;
namespace AnotherAForge
{
public partial class Form1 : Form
{
MotionDetector Detector;
float f;
float MotionDetected;
int frames;
private VideoFileWriter _writer;
private MJPEGStream stream = new MJPEGStream("link to the cam i can't share");
int uporabimotiondetection = 0;
private IVideoSource _videoSource;
public Form1()
{
InitializeComponent();
}
Form form1 = new Form();
public void videoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
{
if (uporabimotiondetection == 1)
{
MotionDetected = Detector.ProcessFrame(image);
//if (label5.InvokeRequired) {
// label5.Text = NivelDeDeteccion.ToString();
//}
//if (Detector.ProcessFrame(image) > 0.02)
//{
// label5.Text = "1";
//}
}
frames++;
}
private void alarm() {
label2.Text = MotionDetected.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
//VideoStream.NewFrame += VideoStream_NewFrame;
//VideoStream.NewFrame += new NewFrameEventHandler(ProcessNewFrame);
stream.Start();
//stream.NewFrame += Stream_NewFrame;
//videoSourcePlayer1.NewFrame += videoSourcePlayer1_NewFrame;
videoSourcePlayer1.VideoSource = stream;
timer1.Enabled = true;
timer1.Start();
timer2.Start();
//pictureBox1.Image = image;
GC.Collect();
}
private void Form1_Load(object sender, EventArgs e)
{
Detector = new MotionDetector(new TwoFramesDifferenceDetector(),new MotionAreaHighlighting());
MotionDetected = 0;
}
private void timer1_Tick(object sender, EventArgs e)
{
// textBox1.Text = NivelDeDeteccion.ToString();
label3.Text = frames.ToString() + " frames";
label2.Text = MotionDetected.ToString();
if (MotionDetected <= 0.02 && MotionDetected >= 0)
{
label5.Text = "1";
}
else {
label5.Text = "0";
}
}
private void button2_Click(object sender, EventArgs e)
{
Console.Beep();
}
int time;
private void timer2_Tick(object sender, EventArgs e)
{
time++;
label4.Text = time.ToString();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
stream.Stop();
}
private void button3_Click(object sender, EventArgs e)
{
stream.Stop();
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked == true)
{
uporabimotiondetection = 1;
}
else {
uporabimotiondetection = 0;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//textBox1.Text = string.Format("{0:0.00000}", textBox1.Text);
//float motionlevel = float.Parse(MotionDetected);
//float a = 1;
//textBox2.Text = a.ToString();
//float b = MotionDetected / 100;
//textBox1.Text = b.ToString();
//double limiter = Convert.ToDouble("0,02");
//textBox2.Text = limiter.ToString();
//if (MotionDetected < (0.02f / 1000))
//{
// label5.Text = "gibanje";
//}
//else
//{
// label5.Text = "ni gibanja!";
//}
}
}
}
I am having a problem . I want to use if statement to check if a button is clicked. For Example:
public void button1_Click(object sender, EventArgs e)
{
while (1)
{
...
...
...
if (Button2 == clicked)
{
break;
}
}
}
But it's not working like this, because the ".click" can only be on the left side of "+=" or "-=". Any idea how i can check if Button2 is clicked?
the code is loking like this: and i want to check button2 to stop the "programm".
the check for the Button2 is nearly at the end of the code ;)
public void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int EmFilterPos;
int ExFilterPos;
string String1;
int[] EmLB = new int[126];
int[] ExLB = new int[126];
int LBEmAnzahl = 0;
int LBEmTot = 0;
int LBExAnzahl = 0;
int LBExTot = 0;
UInt32 C_Zyklen;
UInt32 Zyklen;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_On = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOn;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_Off = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOff;
Roche.DetectionControl2.Device_Filterwheels.fiweGetLBResponse LightBarrier;
string Text = String.Format("Filterrad-Dauertest\r\nGestart am {0:d} um {0:t}\r\n\r\n", DateTime.Now);
System.IO.File.WriteAllText(#"TestLogFile\Filterrad_Dauertest1.txt", Text);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
while (Zyklen <= 20)
{
for (int q=1;q<8;q++)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(q,q);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
for (int w=0;w<7;w++)
{
ExFilterPos = rnd.Next(1,8);
EmFilterPos = rnd.Next(1,8);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
C_Zyklen = Zyklen;
if ((C_Zyklen % 2) < 14)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Init bei: ");
String1 = String.Format("{0,7}",Zyklen);
file.Write(String1);
file.Write(file.NewLine);
}
ExFilterPos = 60;
EmFilterPos = 60;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_On);
while (EmFilterPos != -60)
{
LightBarrier = Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweGetLB();
if (LightBarrier.LBEm == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBEmAnzahl++;
LBEmTot += EmFilterPos;
}
if (LightBarrier.LBEx == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBExAnzahl++;
LBExTot += ExFilterPos;
}
ExFilterPos--;
EmFilterPos--;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
}
EmFilterPos = LBEmTot / LBEmAnzahl;
ExFilterPos = LBExTot / LBExAnzahl;
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Nullstelle Mittelposition Em-Filter: ");
file.Write(EmFilterPos);
file.Write(file.NewLine);
file.Write("Nullstelle Mittelposition Ex-Filter: ");
file.Write(ExFilterPos);
file.Write(file.NewLine);
file.Write(file.NewLine);
}
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_Off);
}
if (Button2 == clicked) // or something like this
break;
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Beendet am {0:d} um {0:t}\r\n", DateTime.Now);
}*/
}
Hm...
bool b1clicked = false, b2clicked = false;
public void button2_Click(object sender, EventArgs e)
{
b2clicked = true;
}
public void button1_Click(object sender, EventArgs e)
{
b1clicked = true;
if (b1clicked && b2clicked)
{
//...
}
}
Beside the weird behavior you want..and since you are not using Threads, you have the following options:
Local functions (.Net > 4.7)
private void B_Click(object sender, EventArgs e)
{
bool clickFlag = false;
void Click(object sender2, EventArgs e2)
{
clickFlag = true;
}
b2.Click += Click;
while (!clickFlag)
{
Thread.Sleep(1);
}
b2.Click -= Click;
//Continue with your stuff
}
Threads
Thread newThread;
private void Button1_Click()
{
newThread = new Thread(YourBreakableProcess);
newThread.Start();
}
private void Button2_Click()
{
newThread.Join();
}
private void YourBreakableProcess()
{
//Your breakable process
}
Async methods.
I hope you find a solution. Cheers.
Edit:
Since what you want is to interrupt the process of whatever you are doing, the only option you have is Local fuctions as shown above, if you are not tied to a specific framework version.
BackgroundWorker and check in every step if the button 2 was pressed with the flag thing mentioned in other answer.
Threads, and make a thread.Join when the button 2 is pressed.
Edit 2:
Updated answer with Threads, I will recommend that if you go with this option it is much better to use a BackgroundWorker instead as you will have the whole control of the process breaking it only in the place where it would be fine to break it.
You can achieve this using a flag variable. Declare and initialize flag value to false.On button2 click change flag value to true as follows,
private bool flag= false;
private void button2_Click(object sender, EventArgs e)
{
flag= true;
}
public void button1_Click(object sender, EventArgs e)
{
//Use flag to check whether button 2 has clicked or not
if (flag)
{
}
else
{
}
}
Can you help? In C#, after clicking on button1, checkBoxWMVFile (the time interval)
should be switched on and off.
private void button1_Click(object sender, EventArgs e)
{
if (timercheckbox.Enabled == true)
{
timercheckbox = new Timer();
timercheckbox.Start();
timercheckbox.Interval = 10000; // 10 second
if(timercheckbox.Enabled)
{
timercheckbox.Start();
checkBoxWMVFile.Checked = true;
}
else
{
timercheckbox.Stop();
checkBoxWMVFile.Checked = false;
}
}
}
As I understood, you need something like this
private Timer _timer = new Timer();
public Form1()
{
InitializeComponent();
_timer.Interval = 10000;
_timer.Tick += new EventHandler(_timer_Tick);
}
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
checkBox1.Checked = false;
if(_timer.Enabled)
_timer.Stop();
}
else
{
checkBox1.Checked = true;
if (!_timer.Enabled)
_timer.Start();
}
}
void _timer_Tick(object sender, EventArgs e)
{
//do something here
throw new NotImplementedException();
}
In order for your code to work, you have to reverse the logic i.e.
private void button1_Click(object sender, EventArgs e)
{
if(checkBoxWMVFile.Checked == false)//if the textbox is not checked
{
if (timercheckbox == null)//If this is the first time
{
timercheckbox = new Timer();//Create a timer
timercheckbox.Interval = 10000; // Set the interval, before starting it.
timercheckbox.Start();//Start it
}
else timercheckbox.Start();//If it is not the first time, just start it
checkBoxWMVFile.Checked = true;//Check the checkbox
}
else//the checkbox is checked
{
timercheckbox.Stop();//Stop the timer
checkBoxWMVFile.Checked = false;//Uncheck the checkbox
}
}
This code works correctly:
// InitializeComponent
this.timercheckbox.Interval = 5000;
this.timercheckbox.Tick += new System.EventHandler(this.timercheckbox_Tick);
private void timercheckbox_Tick(object sender, EventArgs e)
{
checkBoxWMVFile.Checked = false;
checkBoxWMVFile.Checked = true;
}
private void button1_Click(object sender, EventArgs e)
{
if( timercheckbox.Enabled == true )
{
timercheckbox.Enabled = false;
button1.Text = "Start Auto save";
}
else
{
timercheckbox.Interval = (int)numericChnageTime.Value;
timercheckbox.Enabled = true;
checkBoxWMVFile.Checked = true;
button1.Text = "Stop Auto save";
}
}