Using C#, windows form.
I am trying to make the program automatically select next item on combo box every x seconds and once it reaches the last one, it goes back to the first one on list. i got pretty much everything minus auto combo box selection part. :(
help please.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//pictureBox1.Image = Image.FromFile(#"Z:\DSCF1661.jpg");
DirectoryInfo test = new DirectoryInfo(#"C:\temp");//Assuming Test is your Folder
FileInfo[] Files = test.GetFiles("*.pdf"); //Getting Text files
comboBox1.DataSource = Files;
comboBox1.DisplayMember = "Name";
timerset();
}
public void axSetting()
{
axAcroPDF1.setShowToolbar(false);
axAcroPDF1.setView("FitH");
axAcroPDF1.setPageMode("none");
axAcroPDF1.setLayoutMode("SinglePage");
axAcroPDF1.Show();
}
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
axAcroPDF1.LoadFile(#"C:\temp\" + comboBox1.Text);
axAcroPDF1.src = #"C:\temp\" + comboBox1.Text;
axSetting();
}
//private System.Windows.Forms.Timer timer1;
public void comboBoxSelect()
{
if (comboBox1.SelectedIndex < comboBox1.Count) // this part... :(
{
comboBox1.SelectedIndex += 1;
}
else
{
comboBox1.SelectedIndex = 0;
}
}
public void timerset()
{
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 5000; // in miliseconds
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
comboBoxSelect();
}
This should work:
if(combobox.SelectedIndex < (combobox.Items.Count -1))
{
combobox.SelectedIndex += 1;
}
else
{
combobox.SelectedIndex = 0;
}
Related
I am trying to insert text to a lable, BUT the text has to be inserted slowly/character by character/letter by letter,
kinda like in old MUD games.
So far I have tried doing this:
private void StoryBox_Click(object sender, EventArgs e)
{
string text = StoryBox.Text;
var index = 0;
var timer = new System.Timers.Timer(2000);
timer.Elapsed += delegate
{
if (index < text.Length)
{
index++;
StoryBox.Text = "This should come out pretty slowly ";
}
else
{
timer.Enabled = false;
timer.Dispose();
}
};
timer.Enabled = true;
}
This is what I have gathered from the site but I don't particularly understand why this isn't working.
As you can see it's under StoryBox_Click.
Is there a way to automate this? So when the program is opened, it counts a couple seconds and THEN starts writing the text out.
Try this:
private async void button1_Click(object sender, EventArgs e)
{
string yourText = "This should come out pretty slowly";
label1.Text = string.Empty;
int i = 0;
for (i = 0; i <= yourText.Length - 1; i++)
{
label1.Text += yourText[i];
await Task.Delay(500);
}
}
You can use the Shown-Event of YourForm when you want to start it after your GUI has been opened.
So reusing your provided code and changing a few things this may work for you:
Add private fields to YourForm class:
private Timer _timer;
private int _index;
private string _storyText;
and initialising it in YourForm constructor
public YourForm()
{
InitializeComponent();
// init private fields;
this._index = 0;
this._storyText = "This should come out pretty slowly";
// Timer Interval is set to 1 second
this._timer = new Timer { Interval = 1000 };
// Adding EventHandler to Shown Event
this.Shown += this.YourForm_Shown;
this._timer.Tick += delegate
{
if (this._index < this._storyText.Length)
{
StoryBox.Text += this._storyText[this._index];
this._index++;
}
else
{
this._timer.Stop();
}
};
}
and the Shown event for YourForm:
private void YourForm_Shown(object sender, EventArgs e)
{
this._timer.Start();
}
Here I have a chart (graph1) that normally should add a random point every 1second. but it doesn't... I tried to find out what the problem is but here I don't have anymore ideas...
The timer is started, label1 change every seconds but the chart doesn't change... with button one when I click it adds a new point.
what did I miss? please help... thanks a lot.
namespace Test_Chart1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
graph1.ChartAreas[0].AxisX.ScrollBar.Enabled = true;
graph1.ChartAreas[0].AxisX.IsLabelAutoFit = true;
graph1.ChartAreas[0].AxisX.ScaleView.Size = 40;
System.Timers.Timer _Timer1s = new System.Timers.Timer(1000); //object
_Timer1s.Elapsed += _Timer1sElapsed; //event in object
_Timer1s.Start(); //start counting
}
private void _Timer1sElapsed(object sender, EventArgs e)//Timer each 100ms
{
if (label1.BackColor == Color.Red)
{
label1.BackColor = Color.Blue;
PutValueInGraph1();
}
else label1.BackColor = Color.Red;
}
private void button1_Click(object sender, EventArgs e)
{
PutValueInGraph1();
}
private void PutValueInGraph1()
{
graph1.ChartAreas[0].AxisX.ScrollBar.Enabled = true;
graph1.ChartAreas[0].AxisX.IsLabelAutoFit = true;
graph1.ChartAreas[0].AxisX.ScaleView.Size = 100;
Random Rand_Value = new Random();
int ValueToAdd = Rand_Value.Next(1, 100);
listBox1.Items.Add(ValueToAdd.ToString());
graph1.Series["Data1"].Points.AddY(ValueToAdd);
if (graph1.ChartAreas[0].AxisX.Maximum-10 > graph1.ChartAreas[0].AxisX.ScaleView.Size)
{
graph1.ChartAreas[0].AxisX.ScaleView.Scroll(graph1.ChartAreas[0].AxisX.Maximum);
graph1.Series["Data1"].Points.RemoveAt(0);
}
}
}
}
ok here is the new one:
public partial class Form1 : Form
{
static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
public Form1()
{
InitializeComponent();
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Interval = 1;
}
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
Random Rand_Value = new Random();
int ValueToAdd = Rand_Value.Next(1, 100);
listBox1.Items.Add(ValueToAdd.ToString());
graph1.Series["Data1"].Points.AddY(ValueToAdd);
if (graph1.ChartAreas[0].AxisX.Maximum - 10 > graph1.ChartAreas[0].AxisX.ScaleView.Size)
{
graph1.ChartAreas[0].AxisX.ScaleView.Scroll(graph1.ChartAreas[0].AxisX.Maximum);
graph1.Series["Data1"].Points.RemoveAt(0);
}
}
private void btn_Start_Click_1(object sender, EventArgs e)
{
graph1.ChartAreas[0].AxisX.ScrollBar.Enabled = true;
graph1.ChartAreas[0].AxisX.IsLabelAutoFit = true;
graph1.ChartAreas[0].AxisX.ScaleView.Size = 100;
myTimer.Start();
BlinkLed.BackColor = Color.YellowGreen;
}
private void btn_Stop_Click(object sender, EventArgs e)
{
myTimer.Stop();
BlinkLed.BackColor = Color.AliceBlue;
}
}
Do you think it's better?
What about the changing thread?
If I had a button:
private void PutValueInGraph1()
{
Random Rand_Value = new Random();
int ValueToAdd = Rand_Value.Next(1, 100);
listBox1.Items.Add(ValueToAdd.ToString());
graph1.Series["Data1"].Points.AddY(ValueToAdd);
if (graph1.ChartAreas[0].AxisX.Maximum-10 > graph1.ChartAreas[0].AxisX.ScaleView.Size)
{
graph1.ChartAreas[0].AxisX.ScaleView.Scroll(graph1.ChartAreas[0].AxisX.Maximum);
graph1.Series["Data1"].Points.RemoveAt(0);
}
}
private void button1_Click(object sender, EventArgs e)
{//try to raise exception
PutValueInGraph1();
}
and I change the event like this:
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{//try to raise exception
PutValueInGraph1();
}
The data input accelerate when I'm started the timer and I click all the time on the button1.
Why is there no exception as tom_imk said??
because we can access the same function at the same time....?
Thanks for your answers.
I tried below sample code and it is working fine for me.
public Form7()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
chart1.ChartAreas[0].AxisX.Maximum = 100;
chart1.ChartAreas[0].AxisX.Minimum = 0;
chart1.ChartAreas[0].AxisX.Interval = 1;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
Random Rand_Value = new Random();
int ValueToAdd = Rand_Value.Next(1, 100);
chart1.Series[0].Points.AddY(ValueToAdd);
}
I'm surprised you didn't get an exception. You are manipulating UI elements outside the UI thread, something you musn't do, ever.
Refer to the answer in this question:
How to update the GUI from another thread in C#?
EDIT:
To make clear why the timerelapsed method does not run on the UI thread: It's simply the wrong class that is used here. So the easy solution would be to not created a System.Timers.Timer in the Form-constructor but to drop a timer on the form in the form designer and use that instead. The solution by sowjanya attaluri should be marked as the correct answer.
I am confuse at this one, the windows form called "Contact" sometimes called twice after the "Welcome Screen" and sometimes it ("Contact") is called once only. I am pretty sure that I called the form once only.
Here is the code that I am using:
The form below "WelcomeScreen" is the first one called when run the program:
public partial class WelcomeScreen : Form
{
int timeLeft = 5;
Timer _timer = new Timer();
BackgroundWorker _backgroundWorker = new BackgroundWorker();
public WelcomeScreen()
{
InitializeComponent();
_backgroundWorker.WorkerReportsProgress = true;
_backgroundWorker.DoWork += BackgroundWorker_DoWork;
_backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
_timer.Interval = 1000;
_timer.Tick += Timer_Tick;
}
void WelcomeScreen_Load(object sender, EventArgs e)
{
_backgroundWorker.RunWorkerAsync();
}
void Timer_Tick(object sender, EventArgs e)
{
timeLeft--;
if (timeLeft <= 0)
{
_timer.Stop();
this.Hide();
Contact _contact = new Contact();
_contact.ShowDialog();
this.Close();
}
}
void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
if (e.ProgressPercentage <= 300)
{
_timer.Start();
this.label3.Text = "Completed ( " + timeLeft + " ) ";
this.label4.Text = string.Empty;
}
}
void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= 300; i++)
{
_backgroundWorker.ReportProgress(i);
System.Threading.Thread.Sleep(200);
}
}
The form below "Contact" is called after the "WelcomeScreen":
public partial class Contact : Form
{
const int CP_NOCLOSE_BUTTON = 0x200;
public Contact()
{
InitializeComponent();
}
void Contact_Load(object sender, EventArgs e)
{
SystemManager.SoundEffect();
}
void button1_Click(object sender, EventArgs e)
{
this.Hide();
Loading _loading = new Loading();
_loading.ShowDialog();
this.Close();
}
protected override CreateParams CreateParams
{
get
{
CreateParams myCp = base.CreateParams;
myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON;
return myCp;
}
}
I appreciate your answer!
Thank you
It looks like your Timer is causing the issue, by firing multiple times...
You have this condition inside your timer code:
if (timeLeft <= 0)
And the line before is timeLeft--. After timeLeft becomes 0, it will continue getting smaller (-1, -2, etc) and the form will be shown each time.
A quick fix is to either change the condition to timeLeft == 0 or change the type of timeLeft to a uint. Of course, these are both hacks. The correct fix would be to fix your code to stop the timer from firing when required.
I'm trying to make a slideshow with a mediaElement that shows each image in listbox x seconds.
How do I make my code play each image x seconds before continuing?
This code adds all images to a listbox named Listbox1
Dictionary<string, string> Listbox1Dict = new Dictionary<string, string>();
private void SearchBtn_Click(object sender, RoutedEventArgs e)
{
Listbox1.Items.Clear();
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.SelectedPath = "C:\\";
DialogResult result = folderDialog.ShowDialog();
if (result.ToString() == "OK")
FileNameTextBox.Text = folderDialog.SelectedPath;
string directory = FileNameTextBox.Text;
var files = Directory.GetFiles(directory).Where(name => !name.EndsWith(".ini"));
foreach (string file in files)
{
Listbox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file));
Listbox1Dict.Add(System.IO.Path.GetFileNameWithoutExtension(file), file);
}
}
This code shows all images in fullscreen but it skips everyone to last image at start.
private void button1_Click_1(object sender, RoutedEventArgs e)
{
foreach (var selected in Listbox1.Items)
{
string s = selected.ToString();
if (Listbox1Dict.ContainsKey(s))
{
mediaElement1.Visibility = Visibility.Visible;
SearchBtn.Visibility = Visibility.Hidden;
Listbox1.Visibility = Visibility.Hidden;
FileNameTextBox.Visibility = Visibility.Hidden;
mediaElement1.Source = new Uri(Listbox1Dict[s]);
mediaElement1.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
mediaElement1.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
this.Background = new SolidColorBrush(Colors.Black);
this.WindowStyle = WindowStyle.None;
this.WindowState = WindowState.Maximized;
}
}
}
Tried this code to make the image play one by one but I get an error. Look on comment on code:
private int currentSongIndex = -1;
void mediaElement1next(object sender, EventArgs e)
{
if(currentSongIndex == -1)
{
currentSongIndex = Listbox1.SelectedIndex;
}
currentSongIndex++;
if(currentSongIndex < Listbox1.Items.Count)
{
mediaElement1.Play(Listbox1.Items[currentSongIndex]); // No overload for method 'Play' takes 1 arguments
}
else
{
// last song in listbox has been played
}
}
I think you need a timer to set your next image. Using the code you're currently using, it will iterate through your list and change the image until you get to the end.
Take a look at DispatcherTimer. You could set it so, at each tick, it would change to the next image. Something like this (just writing off my head)
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
Then, inside your eventhandler:
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// get the next image
}
Of course you can use other kinds of timers, but that's the main idea.
Hold your image paths in a list & use the tick event of a timer.
Something like:
List<string> paths = new List<string>();
private void timer1_Tick(object sender, EventArgs e)
{
pictureBox1.Image = getNextImage();
}
private string getNextImage()
{
//code...
}
enter code here
EDIT:
Add a class variable: int index = 0;
On the SearchBtn_Click event, add the results to the list.
//..
foreach (string file in files)
{
paths.Add(file);
}
//..
Then do as I did above and the content of the getNextImage method would be:
private string getNextImage()
{
if(index < paths.Count - 1)
{
index += 1;
}
else
{
index = 0;
}
return paths[index];
}
My idea would be to implement a thread that counted to X and then called a NextImage() function when done.
Something like this:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (Listbox1.Items.Count > 0)
{
if (dispatcherTimer.IsEnabled)
dispatcherTimer.Stop();
else
{
curImage = 0;
dispatcherTimer.Start();
}
}
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
Dispatcher.Invoke((Action)delegate
{
ShowNextImage();
}, null);
}
private void ShowNextImage()
{
if (curImage >= Listbox1.Items.Count)
curImage = 0;
var selected = Listbox1.Items[curImage];
string s = selected.ToString();
if (Listbox1Dict.ContainsKey(s))
{
mediaElement1.Visibility = Visibility.Visible;
SearchBtn.Visibility = Visibility.Hidden;
Listbox1.Visibility = Visibility.Hidden;
FileNameTextBox.Visibility = Visibility.Hidden;
mediaElement1.Source = new Uri(Listbox1Dict[s]);
mediaElement1.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
mediaElement1.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
this.Background = new SolidColorBrush(Colors.Black);
this.WindowStyle = WindowStyle.None;
this.WindowState = WindowState.Maximized;
}
}
and declaration
DispatcherTimer dispatcherTimer = new DispatcherTimer();
int x = 2; //seconds
private int curImage = 0;
and some construct
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, x);
ok i have question, i made this code to play axmediaplayer base on item listed on listbox.
first i make this code to make a list using opendialog :
private string[] files, path;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
files = openFileDialog1.SafeFileNames;
path = openFileDialog1.FileNames;
for (int i = 0; i < files.Length; i++) {
listBox1.Items.Add(files[i]);
}
}
}
and then it play the music when the listbox index changed (when the item on the list box cliked) using this code :
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = path[listBox1.SelectedIndex];
}
it works fine, and then i want player to automove to the next song base on item on my listbox. with using events PlayStateChange, so i make this code
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
if(listBox1.SelectedIndex < files.Length - 1)
{
listBox1.SelectedIndex = listBox1.SelectedIndex + 1;
}
}
}
the selected index change, but the player doesn't auto play the next song. i must click the play button manually in order to play the list. can anyone help me up?
ok i found it, the solution is to add timer before playing the next song.
first im adding timer, that shoud be timer1. and then i change playstate event to something like this :
private void axWindowsMediaPlayer1_PlayStateChange(object sender, axWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
timer1.Interval = 100;
timer1.Enabled = true;
}
}
then on the timer i adding tick event, the tick event is something like this :
private void timer1_Tick(object sender, EventArgs e)
{
if (listBox1.SelectedIndex < files.Length - 1)
{
listBox1.SelectedIndex++;
timer1.Enabled = false;
}
else
{
listBox1.SelectedIndex = 0;
timer1.Enabled = false;
}
}
now its work fine ^^
Below functionality worked for me:
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if ((WMPLib.WMPPlayState)e.newState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
timer1.Interval = 100;
timer1.Start();
timer1.Enabled = true;
timer1.Tick += timer1_Tick;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
/// method to play video list items
myFuntiontoPlayVideo();
timer1.Enabled = false;
}