Changing Image in PictureBox using a Timer c# - c#

I am trying to figure out how to change the images from a file folder that contains the images to be displayed on the PictureBox.
What I am trying to do is, after a given time interval in the timer, the image in the PictureBox will change.
I have my code but it doesn't seem to work because after it displays the first image, it does not change after that. Please feel free to correct me on what I'm doing wrong. Thanks for the help and advice.
public void playImage()
{
int counter = i + 1;
string[] images = Directory.GetFiles(#"C:\Users\Documents\Visual Studio 2008\Projects\UI\UI\bin\\debugIMAGES");
if (counter > images.Length - 1);
counter = 0;
pictureBox1.Image = Image.FromFile(images[counter]);
}

You can make your list of images and the counter Global variables, Then on every timer tick get an img from the list using the counter and increment it.
So you declare your list and counter as global
string[] imges = null;
int counter = 0;
Then on the Form_Load event set up the timer and read the imges from the directory
private void Form9_Load(object sender, EventArgs e)
{
imges = Directory.GetFiles(#"G:\Pics");
Timer T = new Timer();
T.Interval = 500;
T.Tick += new EventHandler(PlayTime);
T.Start();
}
Then on the timer Tick event you change the picture like this :
void PlayTime(object sender, EventArgs e)
{
// pictureBox1.Image = Image.FromFile(imges[counter++]);
pictureBox1.ImageLocation = imges[counter++]; // better to use it this way.
if (counter >= imges.Length) counter = 0; // Handling out of Bounds
}

Related

Why when playing images in a pictureBox1 using a timer the playing is getting very slow?

At the first time when I click the button it's showing the images in the pictureBox1 one by one fast. But then after some images it's getting very slow.
It's showing the images one by one very slow like in slow motion mode.
This is the button click event code:
private void button5_Click(object sender, EventArgs e)
{
_files = new List<FileInfo>();
myTrackPanelss1.trackBar1.Value = 0;
_indx = 0;
_files.AddRange(_fi);
_files = _files.OrderBy(f => f.LastWriteTime).ToList();
button5.ForeColor = Color.Red;
button6.ForeColor = Color.Black;
button7.ForeColor = Color.Black;
timer3.Start();
button6.Enabled = true;
button6.Text = "Pause";
button7.Enabled = true;
}
The variable _indx is global int.
Then the timer3 tick event:
private void timer3_Tick(object sender, EventArgs e)
{
try
{
myTrackPanelss1.trackBar1.Maximum = _files.Count;
myTrackPanelss1.trackBar1.Minimum = 0;
Image iOLd = this.pictureBox1.Image;
Image img = Image.FromFile(_files[_indx].FullName);
myTrackPanelss1.trackBar1.Value = _indx;
label22.Text = _files[_indx].Name;
this.pictureBox1.Image = img;
if (iOLd != null)
iOLd.Dispose();
_indx++;
if (_indx >= _files.Count)
{
_indx = 0;
}
timer3.Interval = 40;
}
catch
{
}
}
Sometimes when I click the button once the timer start it's showing the images in the pictureBox1 very slow. Sometimes it's showing them fast like interval 40 and then in some point it's getting slow. I can't figure out why it's getting slow.
Declare what you can outside of the timer. Instantiating variables every tick will cause some throttle.. actually why even store those variables in memory? get rid of iOld and img if you can...
Declared and instantiated outside of function:
myTrackPanelss1.trackBar1.Maximum = _files.Count;
myTrackPanelss1.trackBar1.Minimum = 0;
Timer Tick:
try {
this.pictureBox1.Image = Image.FromFile(_files[_indx].FullName);
timer3.Interval = 40;
_indx++;
}

Oxyplot updating data after the end of method

Could you please tell me why the chart is updated after the last iteration (i = 99)?
private void music_play_button_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 100; i++)
{
(hr_plot.Model.Series[0] as LineSeries).Points[0] = new DataPoint(i, HRConstants.HRMin);
(hr_plot.Model.Series[0] as LineSeries).Points[1] = new DataPoint(i, HRConstants.HRMax);
System.Threading.Thread.Sleep(10);
hr_plot.Model.InvalidatePlot(true);
};
}
The chart should change after every iteration, not after the whole loop. What is the proper solution?
The Buttoneventhandler blocks the UI-Thread while computing the new data points. As consequence, the chart only chances once the eventhandler is finished
Solution:
You could create a new dispatchertimer in your eventhandler and caluclate a single iteration on every timerTick

C# - Updating a Chart in Real-Time

Bear with me, I'm new to Stack Overflow, but have used it as a resource for a long time when researching methods of programming that I'm not fond with.
I read up a tutorial on how to create a graph in a C# Windows Forms Application, and was attempting to find out how to make it update itself in real-time if I ever need to use the graph to plot the total amount of data in a sensor. To test it out, I'm using a timer, ticking at every second (1000ms). And before I can use this with a sensor, I'm having two values automatically increment by 1.
The current problem I'm facing is that the chart itself won't update, and only stays the way it was drawn when the form loaded. I thought it was because I have to redraw the chart with chart1.Update();, and I tried using that before/after recreating the chart every second. However, the result is the same regardless. I just wondered if there's something I haven't done or needs to be changed in order to update the chart in real-time.
This is where the code is at currently:
public partial class Form1 : Form
{
int a = 1;
int b = 2;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Data arrays.
string[] seriesArray = { "Cats", "Dogs" };
int[] pointsArray = { a, b };
// Set palette.
this.chart1.Palette = ChartColorPalette.SeaGreen;
// Set title.
this.chart1.Titles.Add("Pets");
// Add series.
for (int i = 0; i < seriesArray.Length; i++)
{
// Add series.
Series series = this.chart1.Series.Add(seriesArray[i]);
// Add point.
series.Points.Add(pointsArray[i]);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
a++;
b++;
// Data arrays.
string[] seriesArray = { "Cats", "Dogs" };
int[] pointsArray = { a, b };
// Set palette.
this.chart1.Palette = ChartColorPalette.SeaGreen;
// Set title.
this.chart1.Titles.Add("Pets");
// Add series.
for (int i = 0; i < seriesArray.Length; i++)
{
// Add series.
Series series = this.chart1.Series.Add(seriesArray[i]);
// Add point.
series.Points.Add(pointsArray[i]);
}
chart1.Update();
}
}
Your code has several problems:
The timer click event is not hooked up. I know that it isn't because otherwise you'd get an exception telling you that..
..you can add a series only once. You were doing it on each timer.Tick. This and all other setup commands should go into an initial method like the form load.
I have corrected the errors in the code below, but, obviously, the data don't make any sense yet.
Also: While I have added code to hook up the timer.Tick, the button.Click is not hooked up. Usually you let the designer do this by double-clicking the control to hook up the standard event of a control or by double-clicking the event in the control's event tab in the property page.
int a = 1;
int b = 2;
string[] seriesArray = { "Cats", "Dogs" };
private void Form1_Load(object sender, EventArgs e)
{
// Set palette.
this.chart1.Palette = ChartColorPalette.SeaGreen;
// Set title.
this.chart1.Titles.Add("Pets");
// Add series
this.chart1.Series.Clear();
for (int i = 0; i < seriesArray.Length; i++)
{
chart1.Series.Add(seriesArray[i]);
}
// hook up timer event
timer1.Tick += timer1_Tick;
}
private void timer1_Tick(object sender, EventArgs e)
{
a++;
b++;
// Data array
int[] pointsArray = { a, b };
for (int i = 0; i < seriesArray.Length; i++)
{
// Add point.
chart1.Series[i].Points.Add(pointsArray[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
}

Picture unable to be shown in Picture Box from listbox when doing loop C#

Newbie in programming here so please give answers with clear elaboration. Thank you.
When i do this loop for a slideshow with given number of loops, the pictures do not show in the picturebox while the loop is running.
And, i have a selectedindexchanged event somewhere so only when the loop ends, that event fires and only the last picture is shown on the picturebox.
CODE:
if (mtxtloop.Text != "")
{
int intNumberOfLoops = Convert.ToInt16(mtxtloop.Text);
for (int intAlbum = 0; intAlbum < intNumberOfLoops; intAlbum++)
{
for (int intPictures = 0; intPictures < listBoxPicturesInAlbum.Items.Count; intPictures++)
{
//Just to check position.
listboxPicturesInAlbum.SelectedIndex = intPictures;
Thread.Sleep(2000);
//Insert selecteditem into picture
//ERROR HERE: PictureBox doesn't show selecteditem
pBoxOfSelectedPicture.Image = Image.FromFile(listBoxPicturesInAlbum.SelectedItem.ToString());
}
}
}
In your original code you are simply missing a PBox_loop.Refresh();. But you are also tying up the UI thread by sending it to sleep for seconds. Never a good idea.. (Thread.Sleep() can sometimes help resolve race conditions but not here and never for more than 10-100ms)
Here is the way I would do it: Use a Timer and three variables at e.g. class level to keep track of the progress..
int intNumberOfLoops = 1;
int intLoopCounter = 0;
int pictureIndex = 0;
private void startButton_Click(object sender, EventArgs e)
{
pictureIndex = 0;
intLoopCounter = 0;
// insert error checking here!
intNumberOfLoops = Convert.ToInt16(mtxtloop.Text);
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
// final image:
if (intLoopCounter >= intNumberOfLoops)
{ // this assumes there is a selected item!
PBox_loop.ImageLocation = listBoxPicturesInAlbum.SelectedItem.ToString();
timer1.Stop();
return;
}
// the regular loop:
PBox_loop.ImageLocation = listBoxPicturesInAlbum.Items[pictureIndex];
pictureIndex++;
if (pictureIndex >= listBoxPicturesInAlbum.Items.Count)
{
pictureIndex = 0;
intLoopCounter++;
}
}
Using a Timer prevent the UI thread of being blocked without the hassle of starting a Thread of your own..

How to Draw Lines with delay?

How to add a time delay while drawing line in picturebox? I am using C #,visual studio 2010.
Graphics g = picturebox.CreateGraphics();
Pen p = new Pen(Color.Red);
for (int j = 1; j < 10; j++)
{
//Draw Line 1
g.DrawLine(p,j*3,j*3,100,100);
//----->How to put a Delay for 2 seconds So I
// see the first line then see the second after 2 sec
//Draw Line 2
g.DrawLine(p,j*10,j*10,100,100);
}
Use a timer on your drawing form. When you're ready to draw, enable the timer and start keeping track of the various lines that you need to draw (for example, in a list / array). Every time the timer fires draw 1 line in the timer's callback function and increment your "line index" (which line to draw next). When all lines are drawn, disable the timer.
For example:
public partial class DrawingForm : Form
{
Timer m_oTimer = new Timer ();
public DrawingForm ()
{
InitializeComponent ();
m_oTimer.Tick += new EventHandler ( m_oTimer_Tick );
m_oTimer.Interval = 2000;
m_oTimer.Enabled = false;
}
// Enable the timer and call m_oTimer.Start () when
// you're ready to draw your lines.
void m_oTimer_Tick ( object sender, EventArgs e )
{
// Draw the next line here; disable
// the timer when done with drawing.
}
}
You can use a simple Timer (System.Windows.Forms.Timer) and keep track of the current line index.
public partial class Form1 : Form {
private int index;
private void frmBrowser_Load(object sender, EventArgs e) {
index = 0;
timer.Interval = 2000;
timer.Start();
}
private void timer1_Tick(object sender, EventArgs e) {
index++;
pictureBox1.Invalidate();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e) {
Pen p = new Pen(Color.Red);
for (int j = 1; j < index; j++) {
g.DrawLine(p,j*3,j*3,100,100);
g.DrawLine(p,j*10,j*10,100,100);
}
}
}
Wrote this from head, it's not tested.
The suggestions in the other answers that add a pause by using a timer are correct but if you want the drawing of a single line to be shown slowly as well you'll need to do more that that.
You could write your own line drawing method and split the drawing of the line into segments and pause between the segments.
A quick alternative is using WPF instead of WinForms:
Add the line to a Canvas with its start and endpoint at the same position.
Add an animation to the endpoint that will move it to the desired location
Upon completion, do the same thing for the next line.
This way you do not have to write the line drawing code nor the timers.
using System.Threading;
Thread.sleep(2000);

Categories

Resources