Visual studio c# send an input for a game - c#

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

Related

Cant show result in array

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.

Multiple Classes Read From Single Class

I am working on a project which requires to start a Timer on load of the Form1 that increments the TimerCount Property of Class TimeCounter in the tick event.
The Project has also Form2 which when open I want to read the increment updates from TimeCounter class which is being incremented by the Form1 because Form1 is parent and will not close I tried to read from TimeCounter but got default set value which is 0.
Here is code:
Timer Class
public class TimeCounter
{
public int timer=0;
public int TimerCount { get; set; }
public int GetTime()
{
return timer;
}
}
Form1 Increment TimerCount After 1 Second
private void Form1_Load(object sender, EventArgs e)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += timer_Elapsed;
timer.Start();
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
sk++;
Timer t = new Timer();
t.TimerCount = sk;
}
Form2 Which Receive Counter Continuously(But Not Working)
private void Form1_Load(object sender, EventArgs e)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += timer_Elapsed;
timer.Enabled = true;
timer.Start();
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Timer t1 = new Timer();
B01CountDown.Text = t1.GetTime().ToString();
}
You are not passing the Timer object correctly to Form2. You need to pass the instance of Timer being used by form 1 to form 2.
Timer:
public class Timer
{
public int timer = 0;
public int TimerCount { get; set; }
public int GetTime()
{
return timer;
}
}
Form1:
public partial class Form1 : Form
{
private Timer _timer;
public Form1()
{
InitializeComponent();
_timer = new Timer();
timer1.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Tick += timer1_Tick;
}
void timer1_Tick(object sender, EventArgs e)
{
_timer.TimerCount++;
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(_timer);
frm2.ShowDialog();
}
}
Form2:
public partial class Form2 : Form
{
public Timer _timer;
public Form2(Timer timer)
{
InitializeComponent();
_timer = timer;
timer1.Start();
}
private void Form2_Load(object sender, EventArgs e)
{
timer1.Tick += timer1_Tick;
}
void timer1_Tick(object sender, EventArgs e)
{
label1.Text = _timer.TimerCount.ToString();
}
}
Output:
I have modified the code you have posted as follows. If you do not understand, then you need to start learning C#.
TimeCounter:
public class TimeCounter
{
public static int timer = 0;
public static int TimerCount
{
get
{
return timer;
}
set
{
timer = value;
}
}
}
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
new Form2().Show();
}
private void Form1_Load(object sender, EventArgs e)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += timer_Elapsed;
timer.Start();
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
TimeCounter.TimerCount++;
}
}
Form 2:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += timer_Elapsed;
timer.Enabled = true;
timer.Start();
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (B01CountDown.InvokeRequired)
{
B01CountDown.Invoke((MethodInvoker)(() =>
{
B01CountDown.Text = TimeCounter.TimerCount.ToString();
}));
}
}
}
Actually you don't require TimeCounter Class and also Timer in Form2
see below code
Form1
public partial class Form1 : Form
{
int sk = 0;
Form2 form2 = new Form2();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += timer_Elapsed;
timer.Start();
}
private void button1_Click_1(object sender, EventArgs e)
{
form2.Show();
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// Do your Stuff
sk++;
form2.UpdateLabel(sk.ToString());
}
}
Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public void UpdateLabel(string Message)
{
if (B01CountDown.InvokeRequired)
{
B01CountDown.Invoke((MethodInvoker)(() =>
{
B01CountDown.Text = Message;
}));
}
}
}

BackgroundWorker does not fire inside User Control

I am currently creating a Windows Form Application and I am wanting to use a BackgroundWorker. I have created a very simple example which works perfectly:
public partial class Form1 : Form
{
private BackgroundWorker bgw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
bgw.WorkerReportsProgress = true;
bgw.DoWork += new DoWorkEventHandler(DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Completed);
}
private void button1_Click(object sender, EventArgs e)
{
bgw.RunWorkerAsync();
}
private void DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 10; i++)
{
bgw.ReportProgress(i * 10, i.ToString());
Thread.Sleep(1000);
}
}
private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Text = string.Format("{0}% : Message = '{1}'", e.ProgressPercentage, e.UserState.ToString());
}
private void Completed(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Completed");
}
}
Now, when I move the same code to my current application it does not fire. The only difference is that instead of running the code at the Form level, I am attempting to run it inside a custom User Control. As such:
public partial class LobbyForm : UserControl
{
private BackgroundWorker bgw = new BackgroundWorker();
public LobbyForm()
{
InitializeComponent();
bgw.WorkerReportsProgress = true;
bgw.DoWork += new DoWorkEventHandler(DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Completed);
}
public LobbyForm(List<TaskFile> tasks)
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
bgw.RunWorkerAsync();
}
private void DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 10; i++)
{
bgw.ReportProgress(i * 10, i.ToString());
Thread.Sleep(1000);
}
}
private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label5.Text = string.Format("{0}% : Message = '{1}'", e.ProgressPercentage, e.UserState.ToString());
}
private void Completed(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Completed");
}
}
Any thoughts on if I am missing something? Perhaps something I am misunderstanding with attempting to run this from a User Control?
I just copied your code and tested it and it worked perfectly if you drag-drop the user control using the designer.
However, if you create he control at runtime and add it to your form, make sure you're using the correct constructor.
LobbyForm lf = new LobbyForm();
this runs this constructor:
public LobbyForm()
{
InitializeComponent();
bgw.WorkerReportsProgress = true;
bgw.DoWork += new DoWorkEventHandler(DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Completed);
}
and not
LobbyForm lf = new LobbyForm(tasks);
which runs this constructor (that doesn't hook up events):
public LobbyForm(List<string> tasks)
{
InitializeComponent();
}
Solution (Call the default constructor from the second one)
public LobbyForm(List<string> tasks) : this()
{
//InitializeComponent();
}

Elapsed event for the time not working, c#

I am using a timer to output text to textbox every 2 seconds. but it seems that it doesnt work. any idea what is wrong. here is my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static System.Timers.Timer aTimer;
public void BtnGenData_Click(object sender, EventArgs e)
{
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;
}
public static void OnTimedEvent(object source, ElapsedEventArgs e)
{
string GenData = "Welcome";
Form1 frm1 = new Form1();
frm1.TboxData.AppendText(GenData.ToString());
}
}
Actually i dont see any output coming.
Although this is not straightly connected with the problem you have in your code, but...
From MSDN System.Timers.Timer:
The server-based Timer is designed for use with worker threads in a
multithreaded environment.
In Windows Forms you can use System.WindowsForms.Timer:
System.Windows.Forms.Timer timer;
public Form1()
{
InitializeComponent();
timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(timer_Tick);
}
public void BtnGenData_Click(object sender, EventArgs e)
{
BtnGenData.Enabled = false;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
timer.Stop();
BtnGenData.Enabled = true;
//do what you need
}
As for your code, why make the timer static? Try to use this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public System.Timers.Timer aTimer;
public void BtnGenData_Click(object sender, EventArgs e)
{
aTimer = new System.Timers.Timer(10000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 2000;
aTimer.Enabled = true;
}
public void OnTimedEvent(object source, ElapsedEventArgs e)
{
this.TboxData.AppendText("Welcome");
}
}
Also you should take into consideration, what could happen if you pressed the button twice...
The problem is in this method:
public static void OnTimedEvent(object source, ElapsedEventArgs e)
{
string GenData = "Welcome";
Form1 frm1 = new Form1();
frm1.TboxData.AppendText(GenData.ToString());
}
By calling new Form1(); you create a new form. This form is created as hidden, you change the text, but it is not displayed and at the end of this method it is garbage collected. What you want is to reuse your existing one. Completely remove this line and use your existing form. By default the name should be form1
public static void OnTimedEvent(object source, ElapsedEventArgs e)
{
string GenData = "Welcome";
form1.TboxData.AppendText(GenData.ToString());
}

Timer counting in Win8 app

I am building a win8 app which has 3 buttons(Button1, Button2 and StartButton) and timer in it. Button1 and Button2 are disabled. If clicked on StartButton, Button1 is enabled and the number of clicks within 20 secs is counted and displayed in a textblock1. After the timer is over Button1 is disabled and Button2 is enabled and clicks are counted and displayed in textblock2. My problem is that the timer ticks properly for Button1 and not for Button2. Timer becomes faster when button2 is enabled. Can someone help me?
My code is below:
private int count1=0;
private int count2=0;
private int clickCounter = 0;
private int timeLeft;
private DispatcherTimer timer;
private void StartTimer()
{
if (this.timer != null)
{
this.StopTimer();
}
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0,0,0,1);
timer.Tick += timer_Tick;
timer.Start();
}
private void StopTimer()
{
if (this.timer != null)
{
this.timer.Stop();
this.timer = null;
}
}
public void timer_Tick(object sender, object args)
{
if (timeLeft > 0)
{
timeLeft = timeLeft - 1;
timerTextBlock.Text = Convert.ToString(timeLeft);
this.StartButton.IsEnabled = false;
}
else
{
StopTimer();
if (clickCounter==2)
{
ShowResult();
this.Button2.IsEnabled = false;
this.StartButton.IsEnabled = false;
}
else
{
myMsg.Text = "Time's up!";
this.Button1.IsEnabled = false;
this.StartButton.IsEnabled = true;
}
}
}
private void Button1_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
// TODO: Add event handler implementation here.
count1++;
this.textblock1.Text=count1.ToString();
}
private void Button2_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
count2++;
this.textblock2.Text=count2.ToString();
}
public void ResetTimer()
{
timeLeft = 20;
}
private void StartButton_Click(object sender, RoutedEventArgs e)
{
clickCounter++;
if (textblock1.Text == "0")
{
ResetTimer();
StartTimer();
this.Button1.IsEnabled = true;
}
else
{
ResetTimer();
StartTimer();
this.Button2.IsEnabled = true;
}
}
Every time you call the StartTimer Method timer.Tick += timer_Tick; is executed. This means if you call StartTimer the second time, every tick will invoke two events. Split your code like:
private void InitTimer()
{
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0,0,0,1);
timer.Tick += timer_Tick;
}
private void StartTimer()
{
timer.Start();
}
and call InitTimer only ones. Another Option is to unregister your event in if (this.timer != null) with the code timer.Tick -= timer_Tick;
A second point I see is a naming conflict: You've got a private global variable timer and one variable timer in your StartTimer Method.
// Edit: Full updated code:
private int count1=0;
private int count2=0;
private int clickCounter = 0;
private int timeLeft;
private DispatcherTimer timer;
private void StartTimer() {
if (timer == null) {
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0,0,0,1);
timer.Tick += timer_Tick;
}
timer.Stop();
timeLeft = 20;
timer.Start();
}
public void timer_Tick(object sender, object args) {
if (timeLeft > 0) {
timeLeft = timeLeft - 1;
timerTextBlock.Text = Convert.ToString(timeLeft);
} else {
timer.Stop();
if (clickCounter==2) {
ShowResult();
Button2.IsEnabled = false;
StartButton.IsEnabled = false;
} else {
myMsg.Text = "Time's up!";
Button1.IsEnabled = false;
StartButton.IsEnabled = true;
}
}
}
private void Button1_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) {
count1++;
textblock1.Text=count1.ToString();
}
private void Button2_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) {
count2++;
textblock2.Text=count2.ToString();
}
private void StartButton_Click(object sender, RoutedEventArgs e) {
clickCounter++;
StartButton.IsEnabled = false;
if (textblock1.Text == "0"){
Button1.IsEnabled = true;
StartTimer();
} else {
Button2.IsEnabled = true;
StartTimer();
}
}

Categories