Simon Game in C# - c#

I've been creating the game Simon in a windows form using C#. I'm having a problem in the labels that blink to show the pattern. When one label is required to blink twice (because it appears in the pattern twice) it will only blink once. Also, in general the labels will sometimes not blink in the correct order they are meant to (i.e the second in the pattern blinks before the first). Any assistance in how to fix this or in general how to improve on my code would be great. I have only been using C# for the last few weeks and it's part of a university project.
Have attached the code and a picture of what the windows form looks like.
Windows Form
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;
namespace Simon2
{
public partial class Form1 : Form
{
List<int> sequence = new List<int>();
Random rnd = new Random();
int number = 0;
public Form1()
{
InitializeComponent();
sequence.Add(rnd.Next(0, 4));
hey();
}
void hey()
{
foreach (int colour in sequence)
{
switch (colour)
{
case 0: {
timer1.Enabled = true;
break;
}
case 1: {
timer2.Enabled = true;
break;
}
case 2: {
timer3.Enabled = true;
break;
}
case 3: {
timer4.Enabled = true;
break;
}
}
}
}
void pattern(int colour)
{
if (sequence[number] == colour)
{
label1.Text = ("Score: " + sequence.Count);
sequence.Add(rnd.Next(0, 4));
number = 0;
hey();
}
else
{
MessageBox.Show("Fail!");
Application.Exit();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (Red1.BackColor == Color.Transparent)
{
Red1.BackColor = Color.Red;
timer1.Interval = 300;
}
else
{
Red1.BackColor = Color.Transparent;
timer1.Interval = 300;
timer1.Stop();
}
}
private void timer2_Tick(object sender, EventArgs e)
{
if (Blue1.BackColor == Color.Transparent)
{
Blue1.BackColor = Color.Blue;
timer2.Interval = 300;
}
else
{
Blue1.BackColor = Color.Transparent;
timer2.Interval = 300;
timer2.Stop();
}
}
private void timer3_Tick(object sender, EventArgs e)
{
if (Yellow1.BackColor == Color.Transparent)
{
Yellow1.BackColor = Color.Yellow;
timer3.Interval = 300;
}
else
{
Yellow1.BackColor = Color.Transparent;
timer3.Interval = 300;
timer3.Stop();
}
}
private void timer4_Tick(object sender, EventArgs e)
{
if (Green1.BackColor == Color.Transparent)
{
Green1.BackColor = Color.Lime;
timer4.Interval = 300;
}
else
{
Green1.BackColor = Color.Transparent;
timer4.Interval = 300;
timer4.Stop();
}
}
private void Red_Click(object sender, EventArgs e)
{
pattern(0);
}
private void Blue_Click(object sender, EventArgs e)
{
pattern(1);
}
private void Yellow_Click(object sender, EventArgs e)
{
pattern(2);
}
private void Green_Click(object sender, EventArgs e)
{
pattern(3);
}
}
}

I am not familiar with the game itself, my understanding is that one light after the other has to light up.
My suggestion: Use Thread.sleep (UI will not be responsive while this does it's thing), instead of timers, directly in the switch:
switch (colour){
case 0: {
Red1.BackColor = Color.Red;
Thread.Sleep(500);
Red1.BackColor = Color.Transparent;
break;
}
edit:
a better way would be to use a while loop which checks if a certain amount of ms elapsed and put Application.DoEvents(); in there

Related

How can I stop my slider from snapping back with isMoveToPointEnabled = true. (WPF C#)

I am doing a small project for fun where I'm making a local music application (kinda like Spotify), and I would like for the slider I use for the music track (MusicSlider) to snap to where I click my mouse. I know you can do this with isMoveToPointEnabled = true, but since I have a really messy timer_tick (Update) function and whatnot, I haven't found a way of making it work properly.
I have tried for so long, and nothing my small brain comes up with works.
The problem is: Whenever I click on the slider like I should do, It immediately just snaps back.
The code is really messy because of the fact i'm not good at making clean code, and that the code has undergone a lot of brainstorming, and I haven't taken the time to fix it up yet.
Anyways, here is the code:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Music_Application.MVVM.View;
using System.Globalization;
using Music_Application.MVVM.ViewModel;
using Microsoft.Win32;
using System.Windows.Controls.Primitives;
using System.Windows.Media.Animation;
using System.Threading;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
namespace Music_Application
{
public partial class MainWindow : Window
{
bool songProgressDrag;
public bool fadeIn;
public bool fadeOut;
public double i;
StreamWriter? sw;
StreamReader? sr;
System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
public MainWindow()
{
InitializeComponent();
VolumeSlider.Value = Read(VolumeSlider.Value, "./Data/VolumeSave.txt");
MusicPlayer.mediaPlayer.Open(new Uri("./Example Items/Music/NeverGonnaGiveYouUp.mp3", UriKind.RelativeOrAbsolute));
MusicSlider.AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler(WhenMovingMusicSlider), true);
MusicSlider.AddHandler(MouseLeftButtonUpEvent, new MouseButtonEventHandler(SyncMusicProgressToSlider), true);
timer.Interval = TimeSpan.FromSeconds(0.01);
timer.Tick += Update;
timer.Start();
}
private void SongProgress_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double>? e)
{
UpdateSongProgress();
}
private void ChooseSong(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "MP3 files (*.mp3)|*.mp3|All files (*.*)|*.*";
openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog() == true)
{
MusicPlayer.mediaPlayer.Open(new Uri(openFileDialog.FileName));
TagLib.File tagFile = TagLib.File.Create(openFileDialog.FileName);
TagLib.IPicture coverArt = tagFile.Tag.Pictures[0];
if(coverArt != null)
{
MemoryStream ms = new MemoryStream(coverArt.Data.Data);
ms.Seek(0, SeekOrigin.Begin);
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = ms;
bitmap.EndInit();
SongCover.ImageSource = bitmap;
}
SongName.Text = tagFile.Tag.Title;
ArtistName.Text = tagFile.Tag.FirstAlbumArtist;
MusicPlayer.mediaPlayer.Open(new Uri(openFileDialog.FileName, UriKind.RelativeOrAbsolute));
if (MusicPlayer.isPlaying)
{
MusicPlayer.mediaPlayer.Play();
}
MusicSlider.Value = 0;
while(!MusicPlayer.mediaPlayer.NaturalDuration.HasTimeSpan)
{
}
}
}
bool nisse;
private void SyncMusicProgressToSlider(object sender, MouseButtonEventArgs e)
{
while(MusicPlayer.mediaPlayer.Position != TimeSpan.FromSeconds(MusicSlider.Value))
{
MusicPlayer.mediaPlayer.Position = TimeSpan.FromSeconds(MusicSlider.Value);
}
songProgressDrag = false;
}
private void WhenMovingMusicSlider(object sender, MouseButtonEventArgs e)
{
songProgressDrag = true;
}
void Update(object? sender, EventArgs e)
{
if (MusicPlayer.mediaPlayer.NaturalDuration.HasTimeSpan)
{
if (!songProgressDrag && MusicPlayer.isPlaying)
{
MusicSlider.Value = MathF.Round((float)MusicPlayer.mediaPlayer.Position.TotalSeconds);
}
if (MusicPlayer.repeat && MusicSlider.Value == MusicSlider.Maximum && !songProgressDrag)
{
MusicPlayer.mediaPlayer.Position -= MusicPlayer.mediaPlayer.Position;
MusicSlider.Value = 0;
}
if (!MusicPlayer.repeat && MusicSlider.Value == MusicSlider.Maximum && !songProgressDrag)
{
MusicPlayer.mediaPlayer.Position -= MusicPlayer.mediaPlayer.Position;
MusicSlider.Value = 0;
PlayButton.IsChecked = false;
}
}
PlayButton.IsChecked = MusicPlayer.isPlaying;
if (MusicPlayer.isPlaying)
{
PauseIcon.Visibility = Visibility.Visible;
PlayIcon.Visibility = Visibility.Hidden;
}
else
{
PauseIcon.Visibility = Visibility.Hidden;
PlayIcon.Visibility = Visibility.Visible;
}
if (fadeIn)
{
if (MusicPlayer.mediaPlayer.Volume < VolumeSlider.Value / 100)
{
i += VolumeSlider.Value / 100 / 12;
MusicPlayer.mediaPlayer.Volume = i;
}
else
{
MusicPlayer.mediaPlayer.Volume = VolumeSlider.Value / 100;
fadeIn = false;
}
}
if (fadeOut)
{
if (MusicPlayer.mediaPlayer.Volume > 0)
{
i -= VolumeSlider.Value / 100 / 12;
MusicPlayer.mediaPlayer.Volume = i;
}
else
{
MusicPlayer.mediaPlayer.Volume = 0;
MusicPlayer.Pause();
MusicSlider.Value = MathF.Round((float)MusicPlayer.mediaPlayer.Position.TotalSeconds);
fadeOut = false;
}
}
UpdateSongProgress();
}
private void UpdateSongProgress()
{
MusicSlider.Maximum = Convert.ToDouble(MathF.Round((float)MusicPlayer.mediaPlayer.NaturalDuration.TimeSpan.TotalSeconds));
TimeSpan length = TimeSpan.FromSeconds(MathF.Round((float)Convert.ToDouble(MusicPlayer.mediaPlayer.NaturalDuration.TimeSpan.TotalSeconds)));
TimeSpan progress = TimeSpan.FromSeconds(MusicSlider.Value);
string songLength = string.Format("{0:D2}:{1:D2}",
length.Minutes,
length.Seconds);
string songProgress = string.Format("{0:D2}:{1:D2}",
progress.Minutes,
progress.Seconds);
if (songLength.Length == 5 && songLength.StartsWith("0"))
{
SongValueTotal.Text = songLength.Remove(0, 1);
}
else if (songLength.Length == 5 && !songLength.StartsWith("0"))
{
SongValueTotal.Text = songLength;
}
else if (songLength.Length == 8 && songLength.StartsWith("0"))
{
SongValueTotal.Text = songLength.Remove(0, 1);
}
else if (songLength.Length == 8 && !songLength.StartsWith("0"))
{
SongValueTotal.Text = songLength;
}
if (songProgress.Length == 5 && songProgress.StartsWith("0"))
{
SongValueProgress.Text = songProgress.Remove(0, 1);
}
else if (songProgress.Length == 5 && !songProgress.StartsWith("0"))
{
SongValueProgress.Text = songProgress;
}
else if (songProgress.Length == 8 && songProgress.StartsWith("0"))
{
SongValueTotal.Text = songLength.Remove(0, 1);
}
else if (songProgress.Length == 8 && !songProgress.StartsWith("0"))
{
SongValueTotal.Text = songLength;
}
}
private void VolumeChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
MusicPlayer.mediaPlayer.Volume = VolumeSlider.Value / 100;
}
public void Pause(object sender, RoutedEventArgs e)
{
PauseIcon.Visibility = Visibility.Hidden;
PlayIcon.Visibility = Visibility.Visible;
MusicPlayer.isPlaying = false;
fadeOut = true;
fadeIn = false;
i = VolumeSlider.Value / 100;
}
public void Play(object sender, RoutedEventArgs e)
{
PauseIcon.Visibility = Visibility.Visible;
PlayIcon.Visibility = Visibility.Hidden;
if (MusicPlayer.mediaPlayer.NaturalDuration.HasTimeSpan)
{
MusicPlayer.Play();
}
MusicPlayer.isPlaying = true;
fadeIn = true;
fadeOut = false;
i = 0;
}
public void RepeatOn(object sender, RoutedEventArgs e)
{
RepeatButtonDot.Visibility = Visibility.Visible;
MusicPlayer.repeat = true;
}
public void RepeatOff(object sender, RoutedEventArgs e)
{
RepeatButtonDot.Visibility = Visibility.Hidden;
MusicPlayer.repeat = false;
}
protected override void OnClosed(EventArgs e)
{
Write(VolumeSlider.Value, "./Data/VolumeSave.txt");
base.OnClosed(e);
Application.Current.Shutdown();
}
private void Write(object sender, string url)
{
sw = new StreamWriter(url);
sw.WriteLine(sender.ToString());
sw.Close();
}
private double Read(object sender, string url)
{
sr = new StreamReader(url);
sender = Convert.ToDouble(sr.ReadLine());
sr.Close();
return (double)sender;
}
private void FillHomeButton(object sender, RoutedEventArgs e)
{
HomeButtonSelected.Visibility = Visibility.Visible;
HomeButtonUnselected.Visibility = Visibility.Hidden;
HomeButtonText.Foreground = System.Windows.Media.Brushes.White;
}
private void UnfillHomeButton(object sender, RoutedEventArgs e)
{
HomeButtonUnselected.Visibility = Visibility.Visible;
HomeButtonSelected.Visibility = Visibility.Hidden;
HomeButtonText.Foreground = new SolidColorBrush(System.Windows.Media.Color.FromRgb(70,70,70)); /*(Brush) new BrushConverter().ConvertFrom("#b3b3b3");*/
}
private void ExitPlaylistCustomizer(object sender, RoutedEventArgs e)
{
CustomizePlaylistPopup.Visibility = Visibility.Hidden;
}
}
public static partial class MusicPlayer
{
public static bool isPlaying;
public static bool repeat;
public static MediaPlayer mediaPlayer = new MediaPlayer();
public static void Play()
{
var mainWindow = (MainWindow)Application.Current.MainWindow;
if (mediaPlayer.NaturalDuration.HasTimeSpan)
{
mediaPlayer.Play();
}
isPlaying = true;
}
public static void Pause()
{
mediaPlayer.Pause();
isPlaying = false;
}
}
}
And also, here is my slider in xaml in case you need it:
<Slider IsManipulationEnabled="True" TickFrequency="1" x:Name="MusicSlider" ValueChanged="SongProgress_ValueChanged" IsSnapToTickEnabled="True" IsMoveToPointEnabled="True" Style="{StaticResource Horizontal_Slider}"
VerticalAlignment="Center" Margin="50,0,50,0"/>
The movement of slider thumb by clicking slider track seems not fire MouseLeftButtonDownEvent. As a result, you timer logic could revert slider's value before MouseLeftButtonUpEvent is fired.
I have no idea on direct solution for this issue. Perhaps it would be better to sync slider value and media player by ValueChanged event.

Using/adding delegation method and BackgroundWorker to my currently fully working program

I've searched many topics but I can't seem to understand how to replace my existing methods with delegation+timer as I am currently using timer only. Also when adding BackgroundWorker to work with btng that moves the elevator down and opens the doors I get a multi-thread usage error stating that another thread is trying to insertdata in the .accdb where the main thread is recorded. I am adding the code which is not very long but fully working. Could someone give me a hint how to replace my existing methods with delegation and add one or two BackgroundWorkers to help the buttons that move the elevator and still keep the timers, please.
P.S. Do I need to share/change the database connection code in order to make it work with the backgroundworker? I'll add it if necessary. It's another couple of more lines..
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.Speech;
using System.Speech.Synthesis;
using System.Data.OleDb;
namespace rewrite
{
public partial class Form1 : Form
{
//variables
int y_up = 63;
int y_down = 376;
int x_door_left_close = 74;
int x_door_left_open = 12;
int x_door_right_close = 139;
int x_door_right_open = 200;
bool go_up = false;
bool go_down = false;
bool arrived_G = false;
bool arrived_1 = false;
//object
SpeechSynthesizer reader = new SpeechSynthesizer();
public Form1()
{
InitializeComponent();
}
private void timerliftdown_Tick(object sender, EventArgs e)
{
if (picturelift.Top <= y_down)
{
picturelift.Top += 1;
}
else
{
timerliftdown.Enabled = false;
btnup.Enabled = true;
btn1.Enabled = true;
btnclose.Enabled = true;
btnopen.Enabled = true;
btndown.BackColor = Color.Red;
btng.BackColor = Color.Red;
dooropendown();
arrived_G = true;
picturelift.Image = global::rewrite.Properties.Resources.Inside_of_the_lift;
displaypanel.Image = global::rewrite.Properties.Resources.G;
displaytop.Image = global::rewrite.Properties.Resources.G;
displaybottom.Image = global::rewrite.Properties.Resources.G;
}
}
private void timerliftup_Tick(object sender, EventArgs e)
{
if (picturelift.Top >= y_up)
{
picturelift.Top -= 1;
}
else
{
timerliftup.Enabled = false;
btndown.Enabled = true;
btng.Enabled = true;
btnclose.Enabled = true;
btnopen.Enabled = true;
btnup.BackColor = Color.Red;
btn1.BackColor = Color.Red;
dooropenup();
arrived_1 = true;
picturelift.Image = global::rewrite.Properties.Resources.Inside_of_the_lift;
displaypanel.Image = global::rewrite.Properties.Resources._1;
displaytop.Image = global::rewrite.Properties.Resources._1;
displaybottom.Image = global::rewrite.Properties.Resources._1;
}
}
private void dooropendown_Tick(object sender, EventArgs e)
{
if (doorleftdown.Left >= x_door_left_open && doorrightdown.Left <= x_door_right_open)
{
doorleftdown.Left -= 1;
doorrightdown.Left += 1;
}
else
{
timerdooropendown.Enabled = false;
}
}
private void timerdoorclosedown_Tick(object sender, EventArgs e)
{
if (doorleftdown.Left <= x_door_left_close && doorrightdown.Left >= x_door_right_close)
{
doorleftdown.Left += 1;
doorrightdown.Left -= 1;
}
else
{
timerdoorclosedown.Enabled = false;
if (go_up == true)
{
picturelift.Image = global::rewrite.Properties.Resources.lift_transparent;
displaypanel.Image = global::rewrite.Properties.Resources.up;
displaytop.Image = global::rewrite.Properties.Resources.up;
displaybottom.Image = global::rewrite.Properties.Resources.up;
reader.Speak("Going up");
timerliftup.Enabled = true;
go_up = false;
}
}
}
private void dooropenup_Tick(object sender, EventArgs e)
{
if (doorleftup.Left >= x_door_left_open && doorrightup.Left <= x_door_right_open)
{
doorleftup.Left -= 1;
doorrightup.Left += 1;
}
else
{
timerdooropenup.Enabled = false;
}
}
private void timerdoorcloseup_Tick(object sender, EventArgs e)
{
if (doorleftup.Left <= x_door_left_close && doorrightup.Left >= x_door_right_close)
{
doorleftup.Left += 1;
doorrightup.Left -= 1;
}
else
{
timerdoorcloseup.Enabled = false;
if (go_down == true)
{
picturelift.Image = global::rewrite.Properties.Resources.lift_transparent;
displaypanel.Image = global::rewrite.Properties.Resources.down;
displaytop.Image = global::rewrite.Properties.Resources.down;
displaybottom.Image = global::rewrite.Properties.Resources.down;
reader.Speak("Going down");
timerliftdown.Enabled = true;
go_down = false;
}
}
}
private void doorclosedown()
{
reader.Speak("doors closing");
insertdata("door closing #Ground floor");
timerdoorclosedown.Enabled = true;
timerdooropenup.Enabled = false;
}
private void dooropendown()
{
reader.Speak("Ground floor, doors opening");
insertdata("doors opening #Ground floor");
timerdoorclosedown.Enabled = false;
timerdooropendown.Enabled = true;
}
private void doorcloseup()
{
reader.Speak("doors closing");
insertdata("Doors closing #First Floor");
timerdoorcloseup.Enabled = true;
timerdooropenup.Enabled = false;
}
private void dooropenup()
{
reader.Speak("First Floor, doors opening");
insertdata("Doors Opening #First Floor");
timerdoorcloseup.Enabled = false;
timerdooropenup.Enabled = true;
}
private void going_up()
{
go_up = true;
doorclosedown();
btng.Enabled = false;
btndown.Enabled = false;
btnclose.Enabled = false;
btnopen.Enabled = false;
arrived_G = false;
insertdata("Lift going up");
}
private void going_down()
{
go_down = true;
doorcloseup();
btn1.Enabled = false;
btnup.Enabled = false;
btnclose.Enabled = false;
btnopen.Enabled = false;
arrived_1 = false;
insertdata("Lift going down");
}
private void btndown_Click(object sender, EventArgs e)
{
btnup.BackColor = Color.DarkCyan;
going_up();
}
private void btnup_Click(object sender, EventArgs e)
{
btndown.BackColor = Color.DarkCyan;
going_down();
}
private void btn1_Click(object sender, EventArgs e)
{
btn1.BackColor = Color.DarkCyan;
going_up();
}
private void btng_Click(object sender, EventArgs e)
{
btng.BackColor = Color.DarkOrange;
going_down();
}
private void btnclose_Click(object sender, EventArgs e)
{
if (arrived_G == true)
{
doorclosedown();
}
else if (arrived_1 == true)
{
doorcloseup();
}
}
private void btnopen_Click(object sender, EventArgs e)
{
if (arrived_G == true)
{
dooropendown();
}
else if (arrived_1 == true)
{
dooropenup();
}
}
private void btnalarm_Click(object sender, EventArgs e)
{
btnalarm.BackColor = Color.Green;
reader.Speak("Emergency Stop. Please exit carefully.");
insertdata("Emergency Stop!");
timerliftdown.Enabled = false;
timerliftup.Enabled = false;
timerdooropendown.Enabled = true;
timerdooropenup.Enabled = true;
displaypanel.Image = global::rewrite.Properties.Resources.alarmbellbutton;
displaytop.Image = global::rewrite.Properties.Resources.alarmbellbutton;
displaybottom.Image = global::rewrite.Properties.Resources.alarmbellbutton;
}

C#- why the backcolor of the button cannot change after the timer reach its condition?

I having problem on the C# Windows Forms.
I have created a timer and a button to act as a timer lamp.
Now I have created the timer and the timer value can get successfully.
But I dont know why the button backcolor cannot change as the setted on the code.
Below is my whole codes.
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;
namespace TimerLamp
{
public partial class Form1 : Form
{
System.Timers.Timer t;
int s, c, x;
String sec;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
t = new System.Timers.Timer();
t.Interval = 1000; //1s
t.Elapsed += OnTimeEvent;
//t.Enabled = true;
}
private void OnTimeEvent(object sender, System.Timers.ElapsedEventArgs e)
{
s += 1;
sec = s.ToString();
if (s == 23)
{
s = 0;
c += 1;
}
TimerTextBox.Invoke((MethodInvoker)(() => TimerTextBox.Text = s.ToString()));
TimerTextBox.Invoke((MethodInvoker)(() => CounterTextBox.Text = c.ToString()));
sec = s.ToString();
}
private void TurnOnLamp_CheckedChanged(object sender, EventArgs e)
{
if (TurnOnLamp.Checked == true)
{
x = Convert.ToInt16(sec);
if (x >= 0 && x <7)
{
btnLamp.BackColor = Color.Green;
}
if (x > 8 && x < 19)
{
btnLamp.BackColor = Color.Red;
}
else if (x >= 19)
{
btnLamp.BackColor = Color.Green;
}
else
{
btnLamp.BackColor = Color.Red;
}
}
if (TurnOnLamp.Checked == false)
{
btnLamp.BackColor = Color.Red;
}
}
private void btnStart_Click(object sender, EventArgs e)
{
if (btnStart.Text == "Start")
{
t.Start();
if (c >= 30)
{
MessageBox.Show("Limit reached");
return;
}
btnStart.Text = "Stop";
}
else if (btnStart.Text == "Stop")
{
t.Stop();
btnStart.Text = "Start";
}
}
private void btnLamp_Click(object sender, EventArgs e)
{
}
private void TimerTextBox_TextChanged(object sender, EventArgs e)
{
}
private void CounterTextBox_TextChanged(object sender, EventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
t.Stop();
Application.DoEvents();
}
}
}
Can someone help me to solve this problem?
When you press the button once, it starts counting in the btnLamp_Click class. And when the checkbox is checked, the button blinks as following code.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TimerLamp
{
public partial class Form1 : Form
{
Timer t;
int s, c, x;
String sec;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
t = new Timer();
t.Interval = 1000; //1s
t.Tick += OnTimeEvent;
//t.Enabled = true;
}
private void OnTimeEvent(object sender, EventArgs e)
{
s += 1;
sec = s.ToString();
if (s == 9)
{
s = 0;
c += 1;
}
textBox1.Text = "sec = " + sec;
textBox2.Text = "c = " + c;
if (TurnOnLamp.Checked == true)
{
x = s;
if (x == 0) btnLamp.BackColor = Color.Green;
if (x == 2) btnLamp.BackColor = Color.Red;
if (x == 4) btnLamp.BackColor = Color.Blue;
if( x == 6) btnLamp.BackColor = Color.LightCyan;
}
else
{
btnLamp.BackColor = Color.Gray;
}
}
private void btnLamp_Click(object sender, EventArgs e)
{
if (btnLamp.Text == "Start")
{
t.Start();
if (c >= 2)
{
MessageBox.Show("Limit reached");
t.Stop();
}
btnLamp.Text = "Stop";
}
else if (btnLamp.Text == "Stop")
{
t.Stop();
btnLamp.Text = "Start";
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
t.Stop();
Application.DoEvents();
}
}
}

How to make a picturebox move across the panel using buttons

I want to make a program where a picturebox is moving inside of the panel. If a button up is pressed, then it moves only up, if the button down is pressed it moves only down etc. Then there are two buttons true and false, if true is pressed then the timer is working, if the button false is pressed then the timer isn't working.
The problem is that the program does do all of the above, but I can't go and press the button up, then left etc. It only works for one command at a time, and once one of them is pressed, it looks like all of the others aren't working(excluding true and false buttons, those always 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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
bool up = false;
bool down = false;
bool left = false;
bool right = false;
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
bool up = false;
bool down = false;
bool left = false;
bool right = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
if(up){
down = false;
left = false;
right = false;
while (!(pictureBox1.Top==panel1.Top))
{
pictureBox1.Top -= 1;
}
}
else if (down)
{
up = false;
left = false;
right = false;
while (!(pictureBox1.Top+pictureBox1.Height == panel1.Top+panel1.Height-10))
{
pictureBox1.Top += 1;
}
}
else if (right)
{
up = false;
down = false;
left = false;
while (!(pictureBox1.Left + pictureBox1.Width == panel1.Left + panel1.Width-10))
{
pictureBox1.Left += 1;
}
}
else if (left)
{
up = false;
right = false;
down = false;
while (!(pictureBox1.Left == panel1.Left))
{
pictureBox1.Left -= 1;
}
}
}
private void button6_Click(object sender, EventArgs e)
{
up = true;
}
private void button5_Click(object sender, EventArgs e)
{
down = true;
}
private void button4_Click(object sender, EventArgs e)
{
left = true;
}
private void button3_Click(object sender, EventArgs e)
{
right = true;
}
I'm not sure where the problem is. Is it in the bool statements?

Refreshing a chart control

This one is driving me a bit crazy. Any help gratefully received. It's a simple program to receive temperature data from an Arduino based temp sensor, and display it in a graph control on a form. The program works fine, and parses the temp data frame a treat. However..... the graph object doesn't refresh, and the whole point is to show the data over time. I thought that the chart1.DataBind command that I put in forced a refresh. I am using Visual Studio 2013 Express. Any thoughts as to what I am doing wrong very much appreciated.
// Start of program.
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 serial_port_with_events_attempt_4
{
public partial class Form1 : Form
{
string RxString;
int RxRead;
int i;
int RxDec1;
int RxDec2;
int RxDec3;
float RxFloat;
float RxFloat2;
string locnString;
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM8";
serialPort1.BaudRate = 9600;
serialPort1.Open();
if (serialPort1.IsOpen)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
textBox1.ReadOnly = false;
}
}
private void buttonStop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
buttonStart.Enabled = true;
buttonStop.Enabled = false;
textBox1.ReadOnly = true;
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxRead = serialPort1.ReadByte();
this.Invoke(new EventHandler(DisplayText));
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
}
private void DisplayText(object sender, EventArgs e)
{
if (RxRead == 126)
{
textBox1.AppendText(Environment.NewLine);
i = 0;
}
if (i< 23)
{
if (i == 7)
{
if (RxRead == 51) // 51 in this position means that the temp sensor is the one in the wooden box
{
textBox1.AppendText("Temperature in Nick's office = ");
locnString = ("Nick's office");
}
}
if (i == 17)
{
RxDec1 = RxRead - 48; // Read the tens unit
}
if (i == 18)
{
RxDec2 = RxRead - 48; // Read the units
}
if (i == 20)
{
RxDec3 = RxRead - 49; // read the decimal
}
if (i == 22)
{
RxFloat = ((RxDec1 * 10) + RxDec2);
RxFloat2 = RxDec3;
RxFloat2 = RxFloat2 / 10;
RxFloat = RxFloat + RxFloat2;
RxString = RxFloat.ToString();
if (RxFloat < 30 && RxFloat >20)
{
// Put the value in the main text box if it is not corrupt, (checking if the range is reasonable
textBox1.AppendText(RxString); // Frig about to get the reads in the right format and added together
// Add a new line into the temperature database
temperature1DataSetTableAdapters.Temp1TableAdapter temp1tableadapter = new temperature1DataSetTableAdapters.Temp1TableAdapter();
temp1tableadapter.Insert(DateTime.Now, RxFloat, locnString);
}
// Delete any old data.
temperature1DataSetTableAdapters.TempTableAdapter temp2tableadapter = new temperature1DataSetTableAdapters.TempTableAdapter();
temp2tableadapter.DeleteTempQuery();
// The above two lines work, but I need to amend to select on date TODO
chart1.DataBind();
}
}
i=i+1;
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'temperature1DataSet.Temp' table. You can move, or remove it, as needed.
this.tempTableAdapter.Fill(this.temperature1DataSet.Temp);
}
}
}
Cheers,
Nick James

Categories

Resources