How do I change the background image of a Windows phone app - c#

I am developing an WP8 app and would like to change the background image with several images ; setting time as a variable and showing images in C#,

You can use DispatcherTimer class in order to change the images with respect to time.
Let me suggest you the easiest way. Name your images as numbers like
1.jpg,2.jpg,3.jpg etc and put them inside a folder.
Now you can use either random number class to pick the images in random order or can use the following method to get the sequentially:
DispatcherTimer picture_timer = new DispatcherTimer();
Random rnd = new Random();
picture_timer .Interval = new TimeSpan(0, 0, 3);
picture_timer .Tick += timer_Tick;
picture_timer .Start();
void timer_Tick(object sender, object e)
{
int num = rnd.Next(1, 13); // creates a number between 1 and 12
string image_source = "/Assets/"+num+".jpg";
}

Related

Do you have to change the background image every second?

i just started learning c# two month ago, and i got this code for my current project (windows forms) to set the background image:
public FormMain()
{
this.BackgroundImage = Properties.Resources.image;
InitializeComponent();
var timer = new Timer();
////change the background image every second
timer.Interval = 1000;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
//add image in list from resource file.
List<Bitmap> lisimage = new List<Bitmap>();
lisimage.Add(Properties.Resources.image);
var indexbackimage = DateTime.Now.Second % lisimage.Count;
this.BackgroundImage = lisimage[indexbackimage];
}
my question is: do you have to change the background image every second, or is it enough if i just write (i have only one single background image):
public FormMain()
{
this.BackgroundImage = Properties.Resources.image;
InitializeComponent();
}
cause it seems to work.
You would only need a timer like that if you were iterating through a series of images in order to create an animation.
What you have is good enough for setting the image once.
As AaronLS wrote, setting the background once would suffice. I'd go a step further and explain why the extra code you have makes very little sense (assuming this is the entire code).
void timer_Tick(object sender, EventArgs e)
{
//add image in list from resource file.
List<Bitmap> lisimage = new List<Bitmap>(); //this line creates a new list
lisimage.Add(Properties.Resources.image); //fill the NEWLY created list with the one image from the resources
//note, that resources are usually static, so it's always the same resource
var indexbackimage = DateTime.Now.Second % lisimage.Count; //choose an index from the list, but the list only contains that one image, so the index will always be 0
this.BackgroundImage = lisimage[indexbackimage]; //pick the same image that was set initially
}
As you can see, the code is rather nonsensical - it doesn't DO anything. It SEEMS someone wanted to create a mechanism to switch images every second, but even THAT is poorly coded.

How do I make a quick program which goes through a list in a C# Windows Form Application?

I was experimenting with lists in C#'s console application, specifically a randomized int list which had its number order randomized. In this experiment I wanted to go through the randomized values from the list when I pressed enter and when it had shown all the randomized values it would stop. And it worked just as I intended: http://i.imgur.com/bNOYrZp.png[^]
Random r = new Random();
int tempValue;
List<int> number = new List<int>();
number.Add(1);
number.Add(2);
number.Add(3);
number.Add(4);
number.Add(5);
number.Add(6);
number.Add(7);
number.Add(8);
number.Add(9);
number.Add(10);
for (int i = 0; i < 10; i++)
{
tempValue = r.Next(0, number.Count);
Console.WriteLine(number[tempValue]);
number.RemoveAt(tempValue);
Console.ReadLine();
}
Now how do I do a similar thing in C#'s Windows Form Application? Instead of pressing enter to go through the list, I press a button to go through the list, and the order of the values are displayed on a label every time I press this button.
I used a similar code, but it did not work as intended. Instead of going through the randomized values it kept making a new order of values which it kept doing every time I clicked the button. What I want it to do is to go through the randomized values and after it has showed all the 10 randomized values, without duplicates, it stops.
private void button1_Click(object sender, EventArgs e)
{
List<int> number = new List<int>();
Random r = new Random();
int tempValue;
number.Add(1);
number.Add(2);
number.Add(3);
number.Add(4);
number.Add(5);
number.Add(6);
number.Add(7);
number.Add(8);
number.Add(9);
number.Add(10);
for (int i = 0; i < 10; i++)
{
tempValue = r.Next(0, number.Count);
label1.Text = number[tempValue].ToString();
number.Remove(number[tempValue]);
}
}
Since you put the list creation and for loop in the click event, its working "as-coded" (obviously not what you intended).
Remember, the entire click handler runs every time you press the button. So you need to initialize the list elsewhere and then just iterate through it on click. Something like:
private Random rng = new Random();
private List<int> numbers = new List<int>();
private void Form_Loaded(...) //Set to Form's Loaded event
{
number.Add(1);
number.Add(2);
number.Add(3);
number.Add(4);
number.Add(5);
number.Add(6);
number.Add(7);
number.Add(8);
number.Add(9);
number.Add(10);
}
private void button1_click(...)
{
tempValue = rng.Next(0, number.Count);
label1.Text = number[tempValue].ToString();
number.Remove(number[tempValue]);
}
Note that this code will have a few issues once the list runs out, there is no way to re-initialize the list, etc. I leave those as an exercise to you.
Also note that I created one instance of Random and stored it at the class level. In general, you want to use one instance per class to avoid seeding issues (though recreating it in the button click would have technically worked, since you probably can't click the button fast enough).

How to make Dynamic TextBox in C#

I have simple FormApplication script that contains button and some TextBoxs.
I want when click on button, one textbox shows some numbers.
How I can make that dynamic.
private void button1_Click(object sender, EventArgs e)
{
txt3.Text = "";
for (int i = 0; i <50; i++)
{
Random random = new Random();
int randomNumber = random.Next(100, 150);
txt3.Text = randomNumber.ToString();
}
}
Now it waits to loop finished and shows latest number.
I want it shows each number during loop in TextBox seperatly.
Seems using Dynamic TextBox is a bit hard, is there any other solution to show this numbers in main form?
Regards,
you need to do it in separate thread and sleep between each iteration or use a timer.
for example:
private int counter;
Timer t = new Timer();
Random random = new Random();
private void button1_Click(object sender, EventArgs e)
{
t.Interval = 100;
t.Tick += new EventHandler(t_Tick);
counter = 0;
t.Enabled = true;
txt3.Text = "";
}
void t_Tick(object sender, EventArgs e)
{
counter++;
int randomNumber = random.Next(100, 150);
txt3.Text = randomNumber.ToString();
if (counter >= 50)
{
t.Enabled = false;
}
}
remember this is just one example out of million ways to do it. a lot of them are good
another way will be using threads:
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(randomize));
t.Start();
}
private void randomize()
{
Random random = new Random();
txt3.Text = "";
for (int i = 0; i < 50; i++)
{
int randomNumber = random.Next(100, 150);
Invoke(new setTxtHandler(setText), randomNumber.ToString());
Thread.Sleep(100);
}
}
private void setText(string val)
{
txt3.Text = val;
}
private delegate void setTxtHandler(string val);
You have to put the Random outside of the loop since it is seeded with the current time and the loop executes too fast.
Random random = new Random();
for (int i = 0; i <50; i++)
{
int randomNumber = random.Next(100, 150);
txt3.Text = randomNumber.ToString();
}
MSDN
The random number generation starts from a seed value. If the same
seed is used repeatedly, the same series of numbers is generated. One
way to produce different sequences is to make the seed value
time-dependent, thereby producing a different series with each new
instance of Random. By default, the parameterless constructor of the
Random class uses the system clock to generate its seed value, while
its parameterized constructor can take an Int32 value based on the
number of ticks in the current time. However, because the clock has
finite resolution, using the parameterless constructor to create
different Random objects in close succession creates random number
generators that produce identical sequences of random numbers.
However, since the loop executes very fast you won't see each value anyway, only the last.
Now it waits to loop finished and shows latest number.
That's because the operation is single-threaded so there's no UI update until it's completed. How you would change that depends on whether this is a Windows application or a Web application.
If this is, for example, a Windows Forms application then you want to call Application.DoEvents() to update the UI each time the loop iterates:
txt3.Text = randomNumber.ToString();
Application.DoEvents();
This will update the UI's text box each time. (Though it will be very fast, so I doubt you'll even notice it. You might throw in a Thread.Sleep() if you want to slow it down.)
If this is a web application, then you'll want to do this whole thing client-side instead of server-side. This is because "updating the UI" in a web application, at least from the server's perspective, means returning the response and waiting for another request. This would result in a lot of back-and-forth between the browser and the server just for updating a single UI element. (Which, while it would be slow enough that you'd notice it, it would be a terrible UX.) So in this case you'd want to move the code to JavaScript, which has the benefit of not being single-threaded and would update the UI as you expect it to.
You can add a panel and then add textboxes onto it
Random random = new Random();
for (int i = 0; i <50; i++)
{
TextBox t=new TextBox();
int randomNumber = random.Next(100, 150);
t.Text = randomNumber.ToString();
panel.Controls.Add(t);
}
You should you separate thread and calculate numbers there and update UI then, because now your UI will be updated after calculation is finished.
E.g. BackgroundWorker
If you want to show each number in the text box, you will need an additional thread which will run the code you have inside button1_Click. With your current implementation, the GUI will freeze while executing the content. As it's very quick you won't notice it though.
From the additional thread, call invoke when setting txt3 to synchronize with the GUI thread. And add a Thread.Sleep(1000) or similar in the for loop in order to see the numbers change.

C# Slow down random number GUI display

I have an application that generates random numbers for about 20 seconds and shows the random number on the fly in a label in the screen.
I want to show the numbers in the same label but then slow down the display of the numbers so like 5 seconds before stoping the process, the display of the number should smoothly slow down more and more until it stops in the final number. Like a raffle.
Any clue?
I can start by telling you what not do to. Do not use Thread.Sleep -- doing so is almost always a "worst practice" and will make your UI unresponsive.
If you use Thread.Sleep on a second thread, as mcl suggests, you won't freeze your UI but you are burning an extremely expensive thread to do very little work.
If you are using C# 4 or earlier then I would create a timer set to tick, say, four times a second. Handle the tick event, and if enough time has passed since the last tick event, change the label. Or, change the interval of the timer each time it ticks.
If you are using C# 5, you can just use await Task.Delay(x):
async void Animate()
{
int delay = 5;
for(int i = 1; i < 10; ++i)
{
UpdateLabel();
await Task.Delay(delay);
delay = delay * 2;
}
}
So now you start with a 5ms delay, then 10, then 20...
Here's a working program to get you started. It changes the Text of the Form for 3 seconds quickly, after which it gets slower. That's achieved by using one Timer to start decelerating the Timer which shows the random numbers.
public partial class Form1 : Form
{
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer() { Interval = 10 };
System.Windows.Forms.Timer timerForStartingSlowDown = new System.Windows.Forms.Timer() { Interval = 3000 };
bool slow = false;
Random random = new Random();
public Form1()
{
InitializeComponent();
timer.Tick += timer_Tick;
timerForStartingSlowDown.Tick += timerForStartingSlowDown_Tick;
Shown += Form1_Shown;
}
void timerForStartingSlowDown_Tick(object sender, EventArgs e)
{
slow = true;
timerForStartingSlowDown.Enabled = false;
}
void Form1_Shown(object sender, EventArgs e)
{
timer.Enabled = true;
timerForStartingSlowDown.Enabled = true;
}
void timer_Tick(object sender, EventArgs e)
{
if (timer.Interval > 350) timer.Enabled = false;
else
{
if (slow) timer.Interval += 10;
Text = random.Next(1, 100).ToString();
}
}
}
Consider generating those numbers on a different thread. You can use BackgroundWorker for that and report the progress as you generate each number. When you begin to reach the end use Thread.Sleep(miliseconds) to "slow" (freez) the BackgroundWorker's job thread that is generating the numbers for a specified amount of miliseconds increasing those miliseconds as you aproach the final number. That should do the trick.
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
Set the BackgroundWorker to report progress and use that to "push" the generated number to the UI thread.
You can also drag and drop the BackgroundWorker component on your form from the Toolbox.

How to slow down animated gif

I have a WinForms app that displays an animated gif in the simplest possible way - there is a PictureBox that loads the .gif directly.
The code generated by the WinForms designer looks like this:
//
// pictureBoxHomer
//
this.pictureBoxHomer.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.pictureBoxHomer.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxHomer.Image = ((System.Drawing.Image)(resources.GetObject("pictureBoxHomer.Image")));
this.pictureBoxHomer.Location = new System.Drawing.Point(3, 3);
this.pictureBoxHomer.Name = "pictureBoxHomer";
this.pictureBoxHomer.Size = new System.Drawing.Size(905, 321);
this.pictureBoxHomer.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
this.pictureBoxHomer.TabIndex = 0;
this.pictureBoxHomer.TabStop = false;
The image is, of course, this: http://media.tumblr.com/tumblr_m1di1xvwTe1qz97bf.gif
Problem: while this animated gif displays wondrously in the browser, it is running way too fast in the WinForms app, which is not as happy as needed. So:
Question: is there a way to slow down an animated gif in a WinForms app?
I believe the answer is rather image-related than C#. If you edit that specific image in a tool like GIMP and take a look at the layers, you'll see it's a composition of 10 layers (frames) but no "delay time" between them is set - it has (0ms) in layer's attribute. You can edit layer's attribute and change it by right-clicking on it and selecting that option in menu. Of course, at the end you have to export your new image and save it as a GIF, selecting "animated" in options.
I believe in this case (when no delay time between frames is specified) web browser and C# PicutureBox force their own,different, default values. So, if you put a delay let say 100ms, like described here in step 3, you'll make the animation slow down.
For future reference, it is possible to override the delay time of a GIF in a picture box. Here is a rough example:
public partial class Form1 : Form
{
private FrameDimension dimension;
private int frameCount;
private int indexToPaint;
private Timer timer = new Timer();
public Form1()
{
InitializeComponent();
dimension = new FrameDimension(this.pictureBox1.Image.FrameDimensionsList[0]);
frameCount = this.pictureBox1.Image.GetFrameCount(dimension);
this.pictureBox1.Paint += new PaintEventHandler(pictureBox1_Paint);
timer.Interval = 100;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
indexToPaint++;
if(indexToPaint >= frameCount)
{
indexToPaint = 0;
}
}
void pictureBox1_Paint(object sender, PaintEventArgs e)
{
this.pictureBox1.Image.SelectActiveFrame(dimension, indexToPaint);
e.Graphics.DrawImage(this.pictureBox1.Image, Point.Empty);
}
}

Categories