How to make the answer appear automatically? - c#

I made a master mind game and im stuck with the last part of it. The Question is.. How can i make the 4 small buttons on the right side to Show the answer automatically after pressing on "2nd row button" (btnRow2)? Right now, my code is working perfectly except the fact that i have to press on the answer Buttons in order to check if the Colors choosen by me are correct or not, i want them to appear automatically without pressing on the buttons.
My 2nd Row Button code
}
private void btnRow2_Click(object sender, EventArgs e)
{
btnChange1_1.Enabled = false;
btnChange1_2.Enabled = false;
btnChange1_3.Enabled = false;
btnChange1_4.Enabled = false;
btnChange2_1.Enabled = true;
btnChange2_2.Enabled = true;
btnChange2_3.Enabled = true;
btnChange2_4.Enabled = true;
btnRow2.Visible = false;
pictureBox2.Visible = true;
pictureBox1.Visible = false;
btnAnswer1_1.Visible = true;
btnAnswer1_2.Visible = true;
btnAnswer1_3.Visible = true;
btnAnswer1_4.Visible = true;
}
All small Answer boxes:
}
private void btnAnswer1_1_Click(object sender, EventArgs e)
{
if (btnChange1_1.BackColor == button1.BackColor)
{
btnAnswer1_1.BackColor = Color.Black;
}
if (btnChange1_1.BackColor == button2.BackColor)
{
btnAnswer1_1.BackColor = Color.Red;
}
if (btnChange1_1.BackColor == button3.BackColor)
{
btnAnswer1_1.BackColor = Color.Red;
}
if (btnChange1_1.BackColor == button4.BackColor)
{
}
{
btnChange1_4.Enabled = false;
btnChange1_3.Enabled = false;
btnChange1_2.Enabled = false;
btnChange1_1.Enabled = false;
}
}
private void btnAnswer1_2_Click(object sender, EventArgs e)
{
if (btnChange1_2.BackColor == button1.BackColor)
{
btnAnswer1_2.BackColor = Color.Red;
}
if (btnChange1_2.BackColor == button2.BackColor)
{
btnAnswer1_2.BackColor = Color.Black;
}
if (btnChange1_2.BackColor == button3.BackColor)
{
btnAnswer1_2.BackColor = Color.Red;
}
if (btnChange1_2.BackColor == button4.BackColor)
{
btnAnswer1_2.BackColor = Color.Red;
{
btnChange1_4.Enabled = false;
btnChange1_3.Enabled = false;
btnChange1_2.Enabled = false;
btnChange1_1.Enabled = false;
}
}
}
private void btnAnswer1_3_Click(object sender, EventArgs e)
{
if (btnChange1_3.BackColor == button1.BackColor)
{
btnAnswer1_3.BackColor = Color.Red;
}
if (btnChange1_3.BackColor == button2.BackColor)
{
btnAnswer1_3.BackColor = Color.Red;
}
if (btnChange1_3.BackColor == button3.BackColor)
{
btnAnswer1_3.BackColor = Color.Black;
}
if (btnChange1_3.BackColor == button4.BackColor)
{
btnAnswer1_3.BackColor = Color.Red;
}
{
btnChange1_4.Enabled = false;
btnChange1_3.Enabled = false;
btnChange1_2.Enabled = false;
btnChange1_1.Enabled = false;
}
}
private void btnAnswer1_4_Click(object sender, EventArgs e)
{
if (btnChange1_4.BackColor == button1.BackColor)
{
btnAnswer1_4.BackColor = Color.Red;
}
if (btnChange1_4.BackColor == button2.BackColor)
{
btnAnswer1_4.BackColor = Color.Red;
}
if (btnChange1_4.BackColor == button3.BackColor)
{
btnAnswer1_4.BackColor = Color.Red;
}
if (btnChange1_4.BackColor == button4.BackColor)
{
btnAnswer1_4.BackColor = Color.Black;
}
{
btnChange1_4.Enabled = false;
btnChange1_3.Enabled = false;
btnChange1_2.Enabled = false;
btnChange1_1.Enabled = false;

Create a method that does what your answer buttons do, and call that method when you press row 2.
That is my suggestions anyway, but I am a bit confused to what you actually want :) GL

Related

How i save and load back and continue the timespan milliseconds value each time running the application again?

the problem is that you can't assign to timespan milliseconds it's read only.
private void UpdateTime()
{
if (ticksDisplayed > 0)
btnReset.Enabled = true;
richTextBox1.Text = GetTimeString(watch.Elapsed);
optionsfile.SetKey("result", result.ToString());
}
private string GetTimeString(TimeSpan elapsed)
{
result = string.Empty;
diff = elapsed.Ticks - previousTicks;
if (radioButton1.Checked == true)
{
ticksDisplayed += diff;
}
else
{
if (countingDown)
{
ticksDisplayed += diff;
}
else
{
ticksDisplayed -= diff;
}
}
if (ticksDisplayed < 0)
{
ticksDisplayed = 0;
watch.Stop();
btnStart.Text = "START";
btnPause.Text = "PAUSE";
btnPause.Enabled = false;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0 && ticksDisplayed == 0)
{
btnReset.Enabled = false;
}
timer1.Enabled = false;
}
ctimeSpan = new TimeSpan(ticksDisplayed);
timeTarget(ctimeSpan);
if (trackBarHours.Value != ctimeSpan.Hours) { trackBarHours.Value = ctimeSpan.Hours; }
if (trackBarMinutes.Value != ctimeSpan.Minutes) { trackBarMinutes.Value = ctimeSpan.Minutes; }
if (trackBarSeconds.Value != ctimeSpan.Seconds) { trackBarSeconds.Value = ctimeSpan.Seconds; }
result = string.Format("{0:00}:{1:00}:{2:00}.{3:000}",
ctimeSpan.Hours,
ctimeSpan.Minutes,
ctimeSpan.Seconds,
ctimeSpan.Milliseconds);
previousTicks = elapsed.Ticks;
return result;
}
calling the UpdateTime here
private void timer1_Tick(object sender, EventArgs e)
{
UpdateTime();
}
saving the timespan milliseconds is not a problem , the problem is how to read it back because you can't assign to ctimeSpan.Milliseconds.
i could save the string.Format variable result again in more places but sometimes result is null if i try to save it in the form1 closed event. so i prefer to save and load back only the ctimeSpan.Milliseconds value in that specific situation.
Editing with the full code of form1 and a screenshot.
Now i'm using the 3 trackBars to save and load the timespan hours,minutes,seconds but because i don't want to add another trackBar for the milliseconds that is the reason i want to save/load the milliseconds separated.
in my application i'm using my own OptionsFile class but it does not matter i want to find the logic and how to save/load the milliseconds separated from the way i'm saving/loading the hours,minutes,seconds.
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.Diagnostics;
using System.IO;
using DannyGeneral;
namespace StopwatchTimer
{
public partial class Form1 : Form
{
private static readonly Stopwatch watch = new Stopwatch();
private long diff = 0, previousTicks = 0, ticksDisplayed = 0;
private OptionsFile optionsfile = new OptionsFile(Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\Settings.txt");
private string result;
private bool runOnStart = false;
private bool countingDown = false;
private TimeSpan ctimeSpan;
public Form1()
{
InitializeComponent();
richTextBox1.TabStop = false;
richTextBox1.ReadOnly = true;
richTextBox1.BackColor = Color.White;
richTextBox1.Cursor = Cursors.Arrow;
richTextBox1.Enter += RichTextBox1_Enter;
trackBarHours.Value = Convert.ToInt32(optionsfile.GetKey("trackbarhours"));
trackBarMinutes.Value = Convert.ToInt32(optionsfile.GetKey("trackbarminutes"));
trackBarSeconds.Value = Convert.ToInt32(optionsfile.GetKey("trackbarseconds"));
richTextBox1.Text = optionsfile.GetKey("result");
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
ticksDisplayed = ctimeSpan.Ticks;
radioButton1.Checked = GetBool("radiobutton1");
timeTargetchkbox.Checked = GetBool("timetargetcheckbox");
timeTargetchkboxState();
if (ticksDisplayed > 0 && radioButton1.Checked == false)
radioButton2.Checked = true;
if (ticksDisplayed == 0)
radioButton1.Checked = true;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0)
{
btnPause.Enabled = false;
btnReset.Enabled = false;
}
else
{
btnPause.Enabled = false;
btnReset.Enabled = true;
}
runOnStart = GetBool("runonstart");
if (runOnStart == true)
{
autoRunOnStart.Checked = true;
StartOnRun();
}
else
{
autoRunOnStart.Checked = false;
}
}
private void timeTargetchkboxState()
{
if (timeTargetchkbox.Checked == false)
{
dateTimePicker1.Enabled = false;
}
else
{
dateTimePicker1.Enabled = true;
}
}
private void RichTextBox1_Enter(object sender, EventArgs e)
{
btnStart.Focus();
}
private void UpdateTime()
{
if (ticksDisplayed > 0)
btnReset.Enabled = true;
richTextBox1.Text = GetTimeString(watch.Elapsed);
optionsfile.SetKey("result", result.ToString());
}
private string GetTimeString(TimeSpan elapsed)
{
result = string.Empty;
diff = elapsed.Ticks - previousTicks;
if (radioButton1.Checked == true)
{
ticksDisplayed += diff;
}
else
{
if (countingDown)
{
ticksDisplayed += diff;
}
else
{
ticksDisplayed -= diff;
}
}
if (ticksDisplayed < 0)
{
ticksDisplayed = 0;
watch.Stop();
btnStart.Text = "START";
btnPause.Text = "PAUSE";
btnPause.Enabled = false;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0 && ticksDisplayed == 0)
{
btnReset.Enabled = false;
}
timer1.Enabled = false;
}
ctimeSpan = new TimeSpan(ticksDisplayed);
timeTarget(ctimeSpan);
if (trackBarHours.Value != ctimeSpan.Hours) { trackBarHours.Value = ctimeSpan.Hours; }
if (trackBarMinutes.Value != ctimeSpan.Minutes) { trackBarMinutes.Value = ctimeSpan.Minutes; }
if (trackBarSeconds.Value != ctimeSpan.Seconds) { trackBarSeconds.Value = ctimeSpan.Seconds; }
result = string.Format("{0:00}:{1:00}:{2:00}.{3:000}",
ctimeSpan.Hours,
ctimeSpan.Minutes,
ctimeSpan.Seconds,
ctimeSpan.Milliseconds);
previousTicks = elapsed.Ticks;
return result;
}
private void timeTarget(TimeSpan ctimeSpan)
{
if (dateTimePicker1.Value.Hour == ctimeSpan.Hours
&& dateTimePicker1.Value.Minute == ctimeSpan.Minutes
&& dateTimePicker1.Value.Second == ctimeSpan.Seconds
&& timeTargetchkbox.Checked == true)
{
//ticksDisplayed = 0;
if (btnPause.Text == "PAUSE")
{
btnPause.Text = "CONTINUE";
watch.Stop();
timer1.Enabled = false;
}
}
else
{
if (btnStart.Text == "STOP")
{
btnPause.Text = "PAUSE";
watch.Start();
timer1.Enabled = true;
}
}
timeTargetchkboxState();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnStart_Click(object sender, EventArgs e)
{
if (btnStart.Text == "START")
{
watch.Reset();
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
diff = 0;
previousTicks = 0;
ticksDisplayed = ctimeSpan.Ticks;
watch.Start();
btnStart.Text = "STOP";
btnPause.Enabled = true;
btnReset.Enabled = true;
timer1.Enabled = true;
}
else
{
watch.Stop();
btnStart.Text = "START";
btnPause.Text = "PAUSE";
btnPause.Enabled = false;
btnReset.Enabled = false;
trackBarHours.Value = 0;
trackBarMinutes.Value = 0;
trackBarSeconds.Value = 0;
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
diff = 0;
previousTicks = 0;
ticksDisplayed = ctimeSpan.Ticks;
watch.Reset();
timer1.Enabled = false;
UpdateTime();
}
}
private void btnReset_Click(object sender, EventArgs e)
{
watch.Reset();
diff = 0;
previousTicks = 0;
ticksDisplayed = 0;
trackBarHours.Value = 0;
trackBarMinutes.Value = 0;
trackBarSeconds.Value = 0;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0)
{
btnReset.Enabled = false;
}
else
{
btnReset.Enabled = true;
}
if (radioButton2.Checked && ticksDisplayed == 0)
{
countingDown = true;
radioButton2.Checked = false;
radioButton1.Checked = true;
}
UpdateTime();
}
private void trackBarHours_Scroll(object sender, EventArgs e)
{
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
TimeSpan htimeSpan = new TimeSpan(ctimeSpan.Days, trackBarHours.Value, ctimeSpan.Minutes, ctimeSpan.Seconds, ctimeSpan.Milliseconds);
ticksDisplayed = htimeSpan.Ticks;
TrackbarsScrollStates();
optionsfile.SetKey("trackbarhours", trackBarHours.Value.ToString());
UpdateTime();
}
private void trackBarMinutes_Scroll(object sender, EventArgs e)
{
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
TimeSpan mtimeSpan = new TimeSpan(ctimeSpan.Days, ctimeSpan.Hours, trackBarMinutes.Value, ctimeSpan.Seconds, ctimeSpan.Milliseconds);
ticksDisplayed = mtimeSpan.Ticks;
TrackbarsScrollStates();
optionsfile.SetKey("trackbarminutes", trackBarMinutes.Value.ToString());
UpdateTime();
}
private void trackBarSeconds_Scroll(object sender, EventArgs e)
{
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
TimeSpan stimeSpan = new TimeSpan(ctimeSpan.Days, ctimeSpan.Hours, ctimeSpan.Minutes, trackBarSeconds.Value, ctimeSpan.Milliseconds);
ticksDisplayed = stimeSpan.Ticks;
TrackbarsScrollStates();
optionsfile.SetKey("trackbarseconds", trackBarSeconds.Value.ToString());
UpdateTime();
}
private void TrackbarsScrollStates()
{
if (trackBarSeconds.Value == 0 && trackBarHours.Value == 0 && trackBarMinutes.Value == 0)
btnReset.Enabled = false;
if (trackBarSeconds.Value > 0 || trackBarHours.Value > 0 || trackBarMinutes.Value > 0)
btnReset.Enabled = true;
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
optionsfile.SetKey("radiobutton1", radioButton1.Checked.ToString());
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
optionsfile.SetKey("trackbarhours", trackBarHours.Value.ToString());
optionsfile.SetKey("trackbarminutes", trackBarMinutes.Value.ToString());
optionsfile.SetKey("trackbarseconds", trackBarSeconds.Value.ToString());
}
private void btnPause_Click(object sender, EventArgs e)
{
Pause();
}
private void Pause()
{
if (btnStart.Text == "STOP")
{
if (btnPause.Text == "PAUSE")
{
btnPause.Text = "CONTINUE";
watch.Stop();
timer1.Enabled = false;
}
else
{
btnPause.Text = "PAUSE";
watch.Start();
timer1.Enabled = true;
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
UpdateTime();
}
private void autoRunOnStart_CheckedChanged(object sender, EventArgs e)
{
if (autoRunOnStart.Checked)
{
runOnStart = true;
}
else
{
runOnStart = false;
}
optionsfile.SetKey("runonstart", runOnStart.ToString());
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
countingDown = false;
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
btnStart.Focus();
timeTarget(ctimeSpan);
}
private void timeTargetchkbox_CheckedChanged(object sender, EventArgs e)
{
if (timeTargetchkbox.Checked == false)
{
dateTimePicker1.Enabled = false;
}
else
{
dateTimePicker1.Enabled = true;
}
optionsfile.SetKey("timetargetcheckbox", timeTargetchkbox.Checked.ToString());
}
private void StartOnRun()
{
watch.Reset();
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
diff = 0;
previousTicks = 0;
ticksDisplayed = ctimeSpan.Ticks;
watch.Start();
btnStart.Text = "STOP";
btnPause.Enabled = true;
btnReset.Enabled = true;
timer1.Enabled = true;
}
private bool GetBool(string keyname)
{
string radiobutton1 = optionsfile.GetKey(keyname);
bool b = false;
if (radiobutton1 != null)
{
bool.TryParse(radiobutton1.Trim(), out b);
}
return b;
}
}
}
and a screenshot showing the application :
I'm going to attempt to generalize as the question doesn't show a clear intent on what is trying to be accomplished and so it's difficult to give a clear answer.
There are many ways to instantiate a new TimeSpan as documented here:
https://learn.microsoft.com/en-us/dotnet/api/system.timespan?view=net-7.0#instantiating-a-timespan-value
If I were trying to persist and load a TimeSpan then I would personally look towards using the ticks value.
e.g.
// Create a TimeSpan to test with.
var randomTimer = Stopwatch.StartNew();
Thread.Sleep((new Random()).Next(1000,5000)); // Wait 1 to 5 second to get a meaningful value in the example TimeSpan.
var myTimeSpanToSave = randomTimer.Elapsed;
// Save the total ticks here.
var totalEllapsedTicks = myTimeSpanToSave.Ticks;
// Load total ticks and instantiate a new TimeSpan
var newTimeSpanFromTicks = new TimeSpan(totalEllapsedTicks);
I'm not sure why you would want to modify just the Millisecond portion of a TimeSpan but assuming there is a valid reason then here are a couple of ideas.
Idea 1 - Create a new TimeSpan using the values from the original object and substituting the Millisecond property only.
var customMilliseconds = 123;
var newTimeSpanWithCustomMilliseconds = new TimeSpan(myOriginalTimeSpan.Days, myOriginalTimeSpan.Hours, myOriginalTimeSpan.Minutes, myOriginalTimeSpan.Seconds, customMilliseconds);
Idea 2 - Use Add to clear the current Millisecond value and insert the loaded value.
var customMilliseconds = new TimeSpan(0, 0, 0, 0, 123);
var oldMillisecondValueToRemove = new TimeSpan(0, 0, 0, 0, myOriginalTimeSpan.Milliseconds);
myOriginalTimeSpan.Add(-oldMillisecondValueToRemove);
myOriginalTimeSpan.Add(customMilliseconds);

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;
}

Admob ads are not showing in Unity, C#

My Admob ads are not showing in my app on Android, I tried everything, different versions of unity, types of ads, re-installation of admob plugin, different combinations of player settings for android compilation.
Log on Unity (I tested it on Android) is:
Dummy IsLoaded
Dummy ShowIntertitial
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using GoogleMobileAds.Api;
public class ControllerMain : MonoBehaviour
{
public Button LV1, LV2, LV3, LV4, LV5, LV6, LV7, LV8, LV9, LV10;
public int ReturnedVal;
private string MyIdA = "ca-app-pub-3940256099942544/1033173318";
//private InterstitialAd fullscreenad;
//private string FullScreenID = "ca-app-pub-3940256099942544/1033173651";
//private BannerView bannerView;
private InterstitialAd InterFULLSC;
void LOV1() {
SceneManager.LoadScene(1);
}
void LOV2()
{
SceneManager.LoadScene(2);
}
void LOV3()
{
SceneManager.LoadScene(3);
}
void LOV4()
{
SceneManager.LoadScene(4);
}
void LOV5()
{
SceneManager.LoadScene(5);
}
void LOV6()
{
SceneManager.LoadScene(6);
}
void LOV7()
{
SceneManager.LoadScene(7);
}
void LOV8()
{
SceneManager.LoadScene(8);
}
void LOV9()
{
SceneManager.LoadScene(9);
}
void LOV10()
{
SceneManager.LoadScene(10);
}
// Start is called before the first frame update
void Start()
{
MobileAds.Initialize(initStatus => { });
this.InterFULLSC = new InterstitialAd(MyIdA);
//LV1.GetComponent<Image>().color = Color.black;
ReturnedVal = GameMonitor.IsPassed;
if (ReturnedVal > 0)
{
AdRequest requ = new AdRequest.Builder().Build();
this.InterFULLSC.LoadAd(requ);
if (this.InterFULLSC.IsLoaded()) {
this.InterFULLSC.Show();
}
//MobileAds.Initialize(appID);
//go
//bannerView = new BannerView("ca-app-pub-3940256099942544/6300978111", AdSize.Banner, AdPosition.Bottom);
//AdRequest requ = new AdRequest.Builder().Build();
//bannerView.LoadAd(requ);
//bannerView.Show();
//end
//fullscreenad = new InterstitialAd(FullScreenID);
//AdRequest request = new AdRequest.Builder().Build();
//fullscreenad.LoadAd(request);
//if (fullscreenad.IsLoaded())
//{
// fullscreenad.Show();
//}
//else { Debug.Log("Didn't load"); }
}
Debug.Log(ReturnedVal);
LV1.GetComponent<Image>().color = Color.green;
LV2.GetComponent<Image>().color = Color.black;
LV3.GetComponent<Image>().color = Color.black;
LV4.GetComponent<Image>().color = Color.black;
LV5.GetComponent<Image>().color = Color.black;
LV6.GetComponent<Image>().color = Color.black;
LV7.GetComponent<Image>().color = Color.black;
LV8.GetComponent<Image>().color = Color.black;
LV9.GetComponent<Image>().color = Color.black;
LV10.GetComponent<Image>().color = Color.black;
LV2.interactable = false;
LV3.interactable = false;
LV4.interactable = false;
LV5.interactable = false;
LV6.interactable = false;
LV7.interactable = false;
LV8.interactable = false;
LV9.interactable = false;
LV10.interactable = false;
LV1.interactable = true;
LV1.onClick.AddListener(LOV1);
if (ReturnedVal == 2 || ReturnedVal>2) {
LV2.interactable = true;
LV2.GetComponent<Image>().color = Color.green;
LV2.onClick.AddListener(LOV2);
}
if (ReturnedVal == 3 || ReturnedVal > 3)
{
LV3.interactable = true;
LV3.GetComponent<Image>().color = Color.green;
LV3.onClick.AddListener(LOV3);
}
if (ReturnedVal == 4 || ReturnedVal > 4)
{
LV4.interactable = true;
LV4.GetComponent<Image>().color = Color.green;
LV4.onClick.AddListener(LOV4);
}
if (ReturnedVal == 5 || ReturnedVal > 5)
{
LV5.interactable = true;
LV5.GetComponent<Image>().color = Color.green;
LV5.onClick.AddListener(LOV5);
}
if (ReturnedVal == 6 || ReturnedVal > 6)
{
LV6.interactable = true;
LV6.GetComponent<Image>().color = Color.green;
LV6.onClick.AddListener(LOV6);
}
if (ReturnedVal == 7 || ReturnedVal > 7)
{
LV7.interactable = true;
LV7.GetComponent<Image>().color = Color.green;
LV7.onClick.AddListener(LOV7);
}
if (ReturnedVal == 8 || ReturnedVal > 8)
{
LV8.interactable = true;
LV8.GetComponent<Image>().color = Color.green;
LV8.onClick.AddListener(LOV8);
}
if (ReturnedVal == 9 || ReturnedVal > 9)
{
LV9.interactable = true;
LV9.GetComponent<Image>().color = Color.green;
LV9.onClick.AddListener(LOV9);
}
if (ReturnedVal == 10)
{
LV10.interactable = true;
LV10.GetComponent<Image>().color = Color.green;
LV10.onClick.AddListener(LOV10);
}
}
// Update is called once per frame
void Update()
{
}
}
Initialize the ads using the following format:
MobileAds.Initialize(appID);
Also you are trying to load and show the ad together in start function which might be one of the reason for the issue you are facing.
Load the ad in start function but show the ad on any button click by calling the below function
void ShowAd(){
if (this.InterFULLSC.IsLoaded()) {
this.InterFULLSC.Show();
}
}

How can I find if a selection is inside the rubberband selection in a ListView?

I am using the events ItemSelectionChanged and SelectedIndexChanged of the ListView class to answer this question.
The code is below, and the only bug that seems to remain is that I use the 250ms timer also when the user uses rubberband selection, not only for single or double click selection.
internal Form1()
{
InitializeComponent();
t.Tick += T_Tick;
}
internal bool santinela = false;
internal void T_Tick(object sender, EventArgs e)
{
t.Stop();
if (!santinela)
{
bool newVal = selectionChangedItem.Selected;
selectionChangedItem.Checked =
selectionChangedItem.Selected = newVal;
santinela = true;
}
}
internal Timer t = new Timer()
{
Interval = 250
};
internal bool santinela3 = true;
internal void listView1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (santinela3)
{
if (e.CurrentValue == CheckState.Checked)
{
listView1.SelectedIndices.Remove(e.Index);
}
else if (e.CurrentValue == CheckState.Unchecked)
{
listView1.SelectedIndices.Add(e.Index);
}
}
}
internal void listView1_ItemActivate(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
MessageBox.Show(listView1.SelectedItems[0].Text);
}
}
internal ListViewItem selectionChangedItem = null;
internal bool santinela2 = true;
internal void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (!santinela2)
{
return;
}
if (t.Enabled)
{
santinela = true;
t.Stop();
// double click: both clicks must be done in the same place
if (e.Item == selectionChangedItem)
{
if (!e.IsSelected)
{
santinela2 = true;
e.Item.Selected = true;
santinela2 = false;
}
listView1_ItemActivate(sender, EventArgs.Empty);
}
selectionChangedItem = null;
}
else
{
santinela = false;
t.Stop();
selectionChangedItem = e.Item;
t.Start();
}
}
internal void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedIndices.Count == 0)
{
santinela = true;
t.Stop();
selectionChangedItem = null;
santinela3 = false;
for (int i = 0; i < listView1.CheckedItems.Count; ++i)
{
listView1.CheckedItems[i].Checked = false;
}
santinela3 = true;
}
}
The relevant designer code is below:
System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem("item1");
System.Windows.Forms.ListViewItem listViewItem2 = new System.Windows.Forms.ListViewItem("item2");
this.listView1 = new System.Windows.Forms.ListView();
this.SuspendLayout();
//
// listView1
//
this.listView1.CheckBoxes = true;
listViewItem1.StateImageIndex = 0;
listViewItem2.StateImageIndex = 0;
this.listView1.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
listViewItem1,
listViewItem2});
this.listView1.Location = new System.Drawing.Point(12, 12);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(401, 327);
this.listView1.TabIndex = 0;
this.listView1.UseCompatibleStateImageBehavior = false;
this.listView1.ItemActivate += new System.EventHandler(this.listView1_ItemActivate);
this.listView1.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.listView1_ItemCheck);
this.listView1.ItemSelectionChanged += new System.Windows.Forms.ListViewItemSelectionChangedEventHandler(this.listView1_ItemSelectionChanged);
this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);
Update: The issue I am facing because of the timer is that after hovering with the rubberband a ListViewItem, there is the useless delay of the timer before the item gets checked. When the user resizes/moves the rubberband so that the ListViewItem is no longer checked, there is the same delay. If the user does not know of that non-standard delay, the selection can be wrong.

Why does my disableButtons method not work?

I am currently working on a schoolproject for C# and I am making Tic Tac Toe.
I have a little problem though..
My code used to work perfectly fine untill I build in a scoreboard.
I think the scoreboard is overruling the disableButtons.. Before I added the scoreboard it worked perfectly fine..
Can someone look at my code and tell me what's wrong?
It's supposed to work like this:
Play, if there is a winner, disable buttons. Please help me out!
Edit: I don't know why my namespace is in this textfield..
namespace Tic_Tac_Toe
{
public partial class Form1 : Form
{
bool turn = true; //true = x en false = o
int turn_count = 0;
static String player1, player2;
public Form1()
{
InitializeComponent();
}
public static void setPlayerName(String n1, String n2)
{
player1 = n1;
player2 = n2;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Gemaakt door Luca Fraser", "About");
}
private void button_click(object sender, EventArgs e)
{
Button b = (Button)sender;
if (turn)
b.Text = "X";
else
b.Text = "O";
turn = !turn;
b.Enabled = false;
turn_count++;
checkForWinner();
if (turn_count % 2 == 0)
{
lblTurn.Text = player1 + " is aan de beurt";
}
else
{
lblTurn.Text = player2 + " is aan de beurt";
}
}
private void checkForWinner()
{
bool thereIsWinner = false;
//Horizontaal checken
if((btnA1.Text == btnA2.Text) && (btnA2.Text == btnA3.Text) && (!btnA1.Enabled))
thereIsWinner = true;
else if((btnB1.Text == btnB2.Text) && (btnB2.Text == btnB3.Text) && (!btnB1.Enabled))
thereIsWinner = true;
else if((btnC1.Text == btnC2.Text) && (btnC2.Text == btnC3.Text) && (!btnC1.Enabled))
thereIsWinner = true;
//Verticaal checken
if ((btnA1.Text == btnB1.Text) && (btnB1.Text == btnC1.Text) && (!btnA1.Enabled))
thereIsWinner = true;
else if ((btnA2.Text == btnB2.Text) && (btnB2.Text == btnC2.Text) && (!btnA2.Enabled))
thereIsWinner = true;
else if ((btnA3.Text == btnB3.Text) && (btnB3.Text == btnC3.Text) && (!btnA3.Enabled))
thereIsWinner = true;
//Diagonaal checken
if ((btnA1.Text == btnB2.Text) && (btnB2.Text == btnC3.Text) && (!btnA1.Enabled))
thereIsWinner = true;
else if ((btnA3.Text == btnB2.Text) && (btnB2.Text == btnC1.Text) && (!btnC1.Enabled))
thereIsWinner = true;
if (thereIsWinner)
{
disableButtons();
String winner = "";
if (turn)
{
winner = player2;
lblO.Text = (Int32.Parse(lblO.Text) + 1).ToString();
}
else
{
winner = player1;
lblX.Text = (Int32.Parse(lblX.Text) + 1).ToString();
}
MessageBox.Show(winner + " wins!");
}
else
{
if (turn_count == 9)
{
lblDraw.Text = (Int32.Parse(lblDraw.Text) + 1).ToString();
MessageBox.Show("It's a draw!");
}
}
}
private void disableButtons()
{
try
{
foreach (Control c in Controls)
{
Button b = (Button)c;
b.Enabled = false;
}
}
catch { }
}
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
turn = true;
turn_count = 0;
foreach (Control c in Controls)
{
try
{
Button b = (Button)c;
b.Enabled = true;
b.Text = "";
}
catch { }
}
}
private void Form1_Load(object sender, EventArgs e)
{
Form2 formtwo = new Form2();
formtwo.ShowDialog();
lblXcount.Text = player1;
lblOcount.Text = player2;
lblTurn.Text = player1 + " is aan de beurt";
}
private void mouse_enter(object sender, EventArgs e)
{
Button b = (Button)sender;
if (b.Enabled)
{
if (turn)
{
b.Text = "X";
}
else
b.Text = "O";
}
}
private void mouse_leave(object sender, EventArgs e)
{
Button b = (Button)sender;
if (b.Enabled)
{
b.Text = "";
}
}
private void resetWinCountToolStripMenuItem_Click(object sender, EventArgs e)
{
lblO.Text = "0";
lblX.Text = "0";
lblDraw.Text = "0";
}
private void lblOcount_Click(object sender, EventArgs e)
{
}
private void lblOcount_TextChanged(object sender, EventArgs e)
{
}
}
}
Here:
private void disableButtons()
{
try
{
foreach (Control c in Controls)
{
Button b = (Button)c;
b.Enabled = false;
}
}
catch { }
}
When you iterate over a control that is not a Button, you have an exception and the loop ends.
You can try with this:
foreach (Control c in Controls)
{
Button b = c as Button;
if(b != null)
b.Enabled = false;
}
Your existing code tries to parse every control to Button, if it fails and throws exception. You catch it and nothing happens.
Try this code and get only Buttons to disable:
foreach (Button btn in this.Controls.OfType<Button>())
{
btn.Enabled = false;
}
A suggestion: Comment the catch block code while you're developing, because its easy to debug when and where exception occurs.
private void disableButtons()
{
try
{
foreach (Control c in Controls)
{
Button b = c as Button;
if(b != null)
b.Enabled = false;
}
}
catch (Exception e)
{
Console.Writeline(e.ToString());
}
}
You need to check if the control is a button otherwise you will cause an exception to be thrown.
This is a prime example about why it is a BAD idea to swallow exceptions. If you had reported or logged the exception the problem would have been apparent.

Categories

Resources