Cant show result in array - c#

I am new in the programming world and trying to do this little app for the first time working with WPF but I can't "print" my results from an array in the label.
public partial class MainWindow : Window
{
Stopwatch clock = new Stopwatch();
DispatcherTimer tick = new DispatcherTimer();
public int I = 0;
public string[] temporaryResult = new string[5];
public bool start = false;
public MainWindow()
{
InitializeComponent();
updates();
}
private void updates()
{
tick.Start();
tick.Tick += Tick;
}
private void Tick(object? sender, EventArgs e)
{
Display.Content = Math.Round(clock.Elapsed.TotalMilliseconds, 0);
test.Content = temporaryResult[I];
}
private void Start_Click(object sender, RoutedEventArgs e)
{
if (!start)
{
clock.Reset();
clock.Start();
start = true;
}
else
{
clock.Stop();
start = false;
temporaryResult[I] = clock.Elapsed.TotalMilliseconds.ToString();
I++;
Debug.Print(temporaryResult[1]);
}
}
}
In method tick, I try to show my result with
test.Content = temporaryResult[I];
It doesn't work. But when I use
test.Content = temporaryResult[0];
It works at least once.

Thanks for helping Xerillio!
You are incrementing I (I++) after you insert a value at temporaryResult[I] so I points to an empty index.

Related

Visual studio c# send an input for a game

I'm trying to do a program that presses a button, like I would just press it on my own keyboard.
It works perfectly in txt files, or somewhere else, but in game it just doesn't. The game is metin2.
Thank you!
public partial class Form1 : Form
{
int spaceCount = 0;
bool startPressed = false;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (!startPressed)
{
startPressed = true;
Timer timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = 1000;
timer.Enabled = true;
timer.Start();
}
}
void timer_Tick(object sender, EventArgs e)
{
InputSimulator IS;
IS = new InputSimulator();
IS.Keyboard.KeyPress(VirtualKeyCode.SPACE);
Keyboard.KeyPress(Keys.Space);
spaceCount++;
label1.Text = spaceCount.ToString();
}
}
}

increment the textbox using multithreading

I want to create a C# form in which two text box show two different numbers.
After clicking on start button both numbers should start incrementing at same time should increment slowly so we can see them increment and clicking on stop button should stop increment.
Both text box are not related to each other any way.
public partial class Form1 : Form
{
Thread t1 = new Thread(new ThreadStart(increment1));
public static int fNumber = 0, sNumber = 0,flag = 0;
public Form1()
{
InitializeComponent();
}
private void Start_Click(object sender, EventArgs e)
{
t1.Start();
}
private void button4_Click(object sender, EventArgs e)
{
}
private void number1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
public static void increment1()
{
Form1 frm = new Form1();
for (int i = fNumber;i<1000;i++)
{
frm.number1.Text = Convert.ToString(i);
}
}
}
public void Increment1()
{
for (int i = fNumber;i<1000;i++)
{
number1.Text = Convert.ToString(i);
number2.Text = Convert.ToString(i);
}
}
And just generally avoid static for threads. You can access your textboxes directly without the word this if you named your textboses number1 and number2. In a static method the variables need to be static aswell or you will get a compilation error.
For visibility, functions should have first letter in upper case. So you can distinguish them more easily from variables.
You are creating a new instance of Form1 which is wrong. Use the current Form1 that started the Thread.
Try
public partial class Form1 : Form
{
private Timer timer1;
public static int fNumber = 0, sNumber = 0,flag = 0;
public Form1()
{
timer1 = new Timer();
timer1.Interval = 1000;
timer1.Tick += timer1_Tick;
InitializeComponent();
}
private void Start_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void button4_Click(object sender, EventArgs e)
{
timer1.Stop();
}
private void number1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
int i = 0;
int.TryParse(this.number1.Text, out i);
i++;
if(this.number1.InvokeRequired)
{
this.number1.BeginInvoke((MethodInvoker) delegate()
{
this.number1.Text = Convert.ToString(i);
});
}
else
{
this.number1.Text = Convert.ToString(i);
}
}
}
For safety measures, check if invoking is required.
Replace this.number1.Text = Convert.ToString(i); with this block of code.
if(this.number1.InvokeRequired)
{
this.number1.BeginInvoke((MethodInvoker) delegate()
{
this.number1.Text = Convert.ToString(i);
});
}
else
{
this.number1.Text = Convert.ToString(i);
}

Start timer from different class

In my form I have one button and one label, and in my class I have one timer and it should start with timer.Start();
I need help because I need to start the timer in my form with one button1_Click but I canĀ“t start the timer and where I should have the elapsed event in form or in class timer?
So when I click in the start button in my Form the timer should start, in my Timer.cs, and label in form should show timer time
Timer.CS
public class Timer
{
public string TimerType { get; set; }
public Timer PersonUnlimitedTimer { get; set; }
public enum TypeTimer { Unlimited, Countdown, Limited}
int timervalue;
int minute = 60;
int second = 0;
//Valor a ser alterado pelo user
int final = 1;
public Timer()
{
timervalue = final * minute;
PersonUnlimitedTimer = new Timer();
PersonUnlimitedTimer.Interval = 1000;
PersonUnlimitedTimer.Elapsed += _PersonUnlimitedTimer_Elapsed;
PersonUnlimitedTimer.Start();
}
public Timer(TypeTimer s1)
{
switch (s1)
{
case TypeTimer.Unlimited:
second++;
TimeSpan unlimited_timer = new TimeSpan(0, 0, second);
TimerTime = unlimited_timer.ToString();
break;
case TypeTimer.Countdown:
if (second != timervalue)
{
timervalue--;
TimeSpan countdown_timer = new TimeSpan(0, 0, timervalue);
TimerTime = countdown_timer.ToString();
}
else
{
PersonUnlimitedTimer.Stop();
}
break;
case TypeTimer.Limited:
if (second != timervalue)
{
second++;
TimeSpan limited_timer = new TimeSpan(0, 0, second);
TimerTime = limited_timer.ToString();
}
else
{
PersonUnlimitedTimer.Stop();
}
break;
default:
break;
}
}
public void _PersonUnlimitedTimer_Elapsed(object sender, ElapsedEventArgs e)
{
second++;
TimeSpan unlimited_timer = new TimeSpan(0, 0, second);
TimerTime = unlimited_timer.ToString();
}
}
and this is my form
namespace Time
{
public partial class Timers : Form
{
Timer timer;
public Timers()
{
InitializeComponent();
}
public Timers(Timertimer): this()
{
this.timer= timer;
timer.PersonUnlimitedTimer.Elapsed += PersonUnlimitedTimer_Elapsed;
}
void PersonUnlimitedTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
lblTimerTime.Text = timer.TimerTime;
}
private void Timers_Load(object sender, EventArgs e)
{
}
private void btnStart_Click(object sender, EventArgs e)
{
timer.PersonUnlimitedTimer.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
timer.PersonUnlimitedTimer.Stop();
}
private void btnReset_Click(object sender, EventArgs e)
{
timer.PersonUnlimitedTimer.Stop();
lblTimerTime.Text = "00:00:00";
}
}
}

Paint on next frame on Windows's graphics?

I need to draw some things on the screen for only 1 frame.
Things such as a line of text.
I tried to achieve this with moving windows, but I failed. I cannot get them to show for only 1 frame (8-16 msec), either by showing/hiding or moving in and out of place.
Is there any way to do this?
(Urgh, for the curious, I'm doing this for someone else, so rationalizing over the reason why this needs to be done is useless.)
Edit: Last thing I tried:
public partial class Form2 : Form
{
static Random rand = new Random();
public void ShowString(string s)
{
this.label1.Text = s; // Has .AutoSize = true
this.Size = this.label1.Size;
var bnds = Screen.PrimaryScreen.WorkingArea;
bnds.Size -= this.Size;
this.Location = new Point(rand.Next(bnds.X, bnds.Right), rand.Next(bnds.Y, bnds.Bottom));
}
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (Location.X != -10000 && Location.Y != -10000)
{
Location = new Point(-10000, -10000);
timer1.Interval = Program.interval; // How long to wait before showing two things.
}
else
{
timer1.Interval = Program.delay; // For how long to show.
ShowString("just something to test");
}
}
}
And before that:
public partial class Form2 : Form
{
static Random rand = new Random();
public void ShowString(string s)
{
this.label1.Text = s; // Has .AutoSize = true
this.Size = this.label1.Size;
var bnds = Screen.PrimaryScreen.WorkingArea;
bnds.Size -= this.Size;
this.Location = new Point(rand.Next(bnds.X, bnds.Right), rand.Next(bnds.Y, bnds.Bottom));
}
public Form2()
{
InitializeComponent();
timer1.Interval = Program.interval;
}
private void Form2_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void Form2_Move(object sender, EventArgs e)
{
if (Location.X != -10000 && Location.Y != -10000)
{
Thread.Sleep(Program.delay); // Dirty cheat, but I was just trying.
this.Location = new Point(-10000, -10000);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
ShowString("just something to test");
}
}

How to make labels change in a C#.NET GUI-project

I'm making an application for a friend's birthday, where a window with changing compliments is supposed to pop up.
The window freezes, however, and the labels don't change. I Googled it, and read something about using Backgroundworker in order to seperate the GUI-thread from the changing process.
Still doesn't work.
This is my code:
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.Threading;
namespace ProjectL
{
public partial class Form1 : Form
{
private MessageHandler theHandler = new MessageHandler();
private BackgroundWorker theBackgroundWorker = new BackgroundWorker();
public Form1()
{
InitializeComponent();
}
private void StartButton_Click(object sender, EventArgs e)
{
StartButton.Visible = false;
theBackgroundWorker.DoWork += new DoWorkEventHandler(theBackgroundWorker_doYourWork);
//theBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(theBackgroundWorker_doYourWork);
theBackgroundWorker.RunWorkerAsync();
theHandler.RunMessage(hBDLabel, youAreLabel, mainLabel, this);
}
void theBackgroundWorker_doYourWork(object sender, DoWorkEventArgs e)
{
theHandler.RunMessage(hBDLabel, youAreLabel, mainLabel, this);
}
}
}
This is what's supposed to happen from the background, using a class I've named MessageHandler:
class MessageHandler
{
public List<String> GenerateComplimentTexts()
{
List<String> stringList = new List<String>();
//Adding a bunch of compliments into a List<String>
return stringList;
}
public void RunMessage(Label hBDLabel, Label youAreLabel, Label mainLabel, Form1 form)
{
List<String> stringList = GenerateComplimentTexts();
Thread.Sleep(2000);
form.Text = "Happy Birthday Goose!!!";
hBDLabel.Text = "Happy Birthday Goose!";
Thread.Sleep(3000);
youAreLabel.Text = "You are...";
Thread.Sleep(2000);
foreach (String e in stringList)
{
mainLabel.Text = e;
//form.Test = e
Thread.Sleep(1000);
}
Thread.Sleep(3000);
mainLabel.Text = "";
youAreLabel.Text = FinalMessage;
}
private String _finalMessage = "FINAL MESSAGE";
public String FinalMessage {get {return _finalMessage;}}
}
Still, nothing changes on my window. Everything is pretty much frozen, except for the text in the top-bar of the form itself, if I choose to uncomment
form.Text = e;
Any advice?
You could achieve it using Timers instead of a BackgroundWorker.
It would probably look like this :
MainForm :
public partial class Form1 : Form
{
private Timer timer;
private MessageHandler theHandler = new MessageHandler();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer = new Timer();
timer.Interval = 1000;
timer.Tick += TimerOnTick;
// Initialize the other labels with static text here
}
private void TimerOnTick(object sender, EventArgs eventArgs)
{
theHandler.ShowNext(label1);
}
private void StartButton_Click(object sender, EventArgs e)
{
timer.Start();
}
}
And the MessageHandler class :
public class MessageHandler
{
private List<String> compliments = new List<string>();
private int index = 0;
public MessageHandler()
{
GenerateComplimentTexts();
}
private void GenerateComplimentTexts()
{
List<String> stringList = new List<String>();
//Adding a bunch of compliments into a List<String>
compliments = stringList;
}
public void ShowNext(Label label)
{
label.Text = compliments.ElementAt(index);
index = (index >= compliments.Count - 1) ? 0 : index + 1;
}
}
To update the UI, use the ReportProgress method of the background worker. ReportProgress raises the ProgressChanged event and you can update your UI from there. Be sure to set the WorkerReportsProgress property of the backgroundworker to true.
Try this code:
private void StartButton_Click(object sender, EventArgs e)
{
StartButton.Visible = false;
theBackgroundWorker.DoWork += new DoWorkEventHandler(theBackgroundWorker_doYourWork);
theBackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(theBackgroundWorker_ProgressChanged);
theBackgroundWorker.RunWorkerAsync();
}
void theBackgroundWorker_doYourWork(object sender, DoWorkEventArgs e)
{
var w = sender as BackgroundWorker;
List<String> stringList = GenerateComplimentTexts();
Thread.Sleep(2000);
w.ReportProgress(0, "Happy Birthday Goose!!!");
w.ReportProgress(1, "Happy Birthday Goose!");
Thread.Sleep(3000);
w.ReportProgress(2, "You are...");
Thread.Sleep(2000);
foreach (String e in stringList)
{
w.ReportProgress(3, e);
Thread.Sleep(1000);
}
Thread.Sleep(3000);
w.ReportProgress(3, "");
w.ReportProgress(2, FinalMessage);
}
void theBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
var msg = e.UserState.ToString();
switch (e.ProgressPercentage)
{
case 0:
form.Text = msg;
break;
case 1:
hBDLabel.Text=msg;
break;
case 2:
youAreLabel.Text =msg;
break;
case 3:
mainLabel.Text=msg;
break;
}
}
Have a try with this:
1.) Copy Timer to Form
2.) Copy the following Code into the timer1_tick-Event.
private int _counter;
private int _currentIndex;
private void timer1_Tick(object sender, EventArgs e)
{
switch (_counter)
{
case 1:
form.Text = "Happy Birthday Goose!!!";
hBDLabel.Text = "Happy Birthday Goose!";
break;
case 2:
timer1.Interval = 3000;
break;
case 3:
youAreLabel.Text = "You are...";
break;
case 4:
if (stringlist.count = (_currentIndex -1))
{
timer1.Enabled = false;
}else {
mainLabel.Text = e;
timer1.Interval = 1000;
return;
}
break;
}
_counter ++;
}
Not the most elegant way, but it should work.

Categories