I'm making a pong game in windows forms and I can't figure out how to unpause after pausing in my gameplay form. After pausing a pause screen form is started and after clicking unpause it unpauses, however, I don't know how to make the timer start again. Please let me know.
Here's my code:
Gameplay form:
if (isPaused)
Paused();
}
private void Paused()
{
gameTimer.Stop();
PausedScreen pausedWindow = new PausedScreen();
pausedWindow.Show();
isPaused = false;
}
Pause Screen form:
public PausedScreen()
{
InitializeComponent();
}
private void UnPause(object sender, EventArgs e)
{
Hide();
//Resume timer
}
private void QuitGame(object sender, EventArgs e)
{
Application.Exit();
}
You can catch the event "Closed" when your pausedScreen is closed and then restart the timer in this function.
gameTimer.Stop();
PausedScreen pausedWindow = new PausedScreen();
pausedWindow.Show();
isPaused = false;
pausedWindow.Closed += new EventHandler(Closed);
private void Closed(object sender, EventArgs e){
gametimer.Start();
}
Hope this solves your problem.
Related
I am currently working with WmpLib.WindowsMediaPlayer () but when I click on play after clicking pause the music starts again at the beginning instead of continuing and I do not understand why.
Could someone explain to me?
private void play_Click(object sender, EventArgs e)
{
player = new WMPLib.WindowsMediaPlayer();
player.URL = SoundFilePath;
player.controls.play();
}
private void pause_Click(object sender, EventArgs e)
{
player.controls.pause();
}
I've created a bool value named musiclose. I'm planning if this musiclose value is true, player will close, else it will continue playing.
public static bool musiclose;
Timer code is below:
timer1.Interval = 1000;
timer1.Start();
Here is the code:
public void timer3_Tick(object sender, EventArgs e)
{
SoundPlayer player = new SoundPlayer(#"C:\Path\To\intro.wav");
if (musiclose)
{
player.Stop();
musiclose = false;
}
}
How can I do that??
1) Do not recreate SoundPlayer instance everytime inside timer3_Tick() event. Create a global instance of SoundPlayer.
2) Implement form closing event, https://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing(v=vs.110).aspx
3) In the close event,
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
player.Stop();
player.Dispose();
}
I've made this program in C#:
namespace Spammer
{
public partial class Form1 : Form
{
int delay, y = 1;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
delay = int.Parse(textBox2.Text);
timer1.Interval = delay;
timer1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
String textt = textBox1.Text;
SendKeys.SendWait(textt);
}
}
}
It works fine most of the time, and it can really send keys quickly.
But when I insert a delay of, for example, 10 MS, it's very hard to click the "Stop" button to stop it. The only way to stop the sending is to close the program and I don't want to do that.
Is there anyway I can send keys very quickly, like 5-10 MS, without it impairing my ability to press the buttons inside the program? I can't click while it's sending quickly...
The problem is that you're using SendWait. That will wait for the target application to respond - and while that's happening, your application won't be able to respond to user input. If you use Send instead of SendWait, your UI thread won't be blocked waiting for the key press to be processed.
I was able to reproduce the issue. The app is sending a keystroke every 10 milliseconds. To me, this is not at all surprising that the app is causing freezes. A keystroke every 10 milliseconds is quite a barrage to the active App. Threading is not going to help. Why is this behavior surprising?
In other words, I don't expect things to work out well when I overload the message pump.
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Spammer//your own namesapce
{
public partial class Form1 : Form
{
int delayInMilliseconds, y = 1;
private Timer timer1;
public Form1()
{
InitializeComponent();
//StartTimerWithThreading();
SetupTimer();
}
void StartTimerWithThreading()
{
Task.Factory.StartNew(() =>
{
SetupTimer();
});
}
void SetupTimer()
{
timer1 = new Timer();//Assume system.windows.forms.timer
textBox2.Text = "10";//new delay
timer1.Tick += timer1_Tick;//handler
}
private void button1_Click(object sender, EventArgs e)
{
delayInMilliseconds = int.Parse(textBox2.Text);
timer1.Interval = delayInMilliseconds;
timer1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
String textt = textBox1.Text;
SendKeys.SendWait(textt);
}
}
}
The simple solution is instead of adding code to a Click event handler for your button, we need a MouseDown event handler:
//MouseDown event handler for the button2
private void button2_MouseDown(object sender, EventArgs e) {
timer1.Enabled = false;
}
Or you can keep using the Click event handler but we send the key only when the MouseButtons is not Left like this:
private void timer1_Tick(object sender, EventArgs e) {
String textt = textBox1.Text;
if(MouseButtons != MouseButtons.Left) SendKeys.Send(textt);
}
//then you can freely click your button to stop it.
I have created a splash screen for a WinForm app. Everything works well until the splash screen is just a form with a background image and a label which has a static text - "Loading..."
I want to update the label continuously (with small delay in between) with texts - "Loading","Loading.","Loading.." and "Loading...". For this I have put the following code in my SplashScreen form:
private void SplashScreen_Load(object sender, EventArgs e)
{
lblLoading.Refresh();
lblLoading.Text = "Loading.";
Thread.Sleep(500);
lblLoading.Refresh();
lblLoading.Text = "Loading..";
Thread.Sleep(500);
lblLoading.Refresh();
lblLoading.Text = "Loading...";
Thread.Sleep(500);
}
Now the Splash Screen doesn't appear until the label in it gets updated to "Loading..."
Please help to let me know what I am doing wrong.
Code in my HomeScreen:
public HomeScreen()
{
//....
this.Load += new EventHandler(HandleFormLoad);
this.splashScreen = new SplashScreen();
}
private void HandleFormLoad(object sender, EventArgs e)
{
this.Hide();
Thread thread = new Thread(new ThreadStart(this.ShowSplashScreen));
thread.Start();
//...Performing tasks to be done while splash screen is displayed
done = true;
this.Show();
}
private void ShowSplashScreen()
{
splashScreen.Show();
while (!done)
{
Application.DoEvents();
}
splashScreen.Close();
this.splashScreen.Dispose();
}
EDIT:
As suggested by some users here I have put the startup tasks in background thread and now I am displaying the Splash Screen from the main thread. But still the same issue persist. Here is the updated code of HomeScreen form:
public HomeScreen()
{
//...
this.Load += new EventHandler(HandleFormLoad);
}
private void HandleFormLoad(object sender, EventArgs e)
{
this.Hide();
SplashScreen sc = new SplashScreen();
sc.Show();
Thread thread = new Thread(new ThreadStart(PerformStartupTasks));
thread.Start();
while (!done)
{
Application.DoEvents();
}
sc.Close();
sc.Dispose();
this.Show();
}
private void PerformStartupTasks()
{
//..perform tasks
done = true;
}
and here's the Splash Screen :
private void SplashScreen_Load(object sender, EventArgs e)
{
lblLoading.Update();
lblLoading.Text = "Loading.";
Thread.Sleep(500);
lblLoading.Update();
lblLoading.Text = "Loading..";
Thread.Sleep(500);
lblLoading.Update();
lblLoading.Text = "Loading...";
Thread.Sleep(500);
}
You want a BackgroundWorker that posts ProgressChanged event, which will update the splash screen. The progress changed object could be a string, for example, that you'll display on your splash screen (back on the GUI thread).
You should handle the splash screen in the main thread, and the background work of initialising in the background thread (just as logixologist commented).
That said, the reason that your changed message doesn't show up is because the main thread is busy so it doesn't handle the events that redraws the control. Calling DoEvents in a background thread will only handle messages in that thread, and the messages to update the splash screen is in the main thread.
The Refresh method only invalidates the control, which would cause it to be redrawn if the main thread handled the event. You can use the Update method to force the redraw of the control:
private void SplashScreen_Load(object sender, EventArgs e)
{
lblLoading.Text = "Loading.";
lblLoading.Update();
Thread.Sleep(500);
lblLoading.Text = "Loading..";
lblLoading.Update();
Thread.Sleep(500);
lblLoading.Text = "Loading...";
lblLoading.Update();
}
But, this is only a workaround for the current code. You should really make the main thread handle the messages.
Thanks to all for answering my questions. Finally my issue is solved ! I changed my code such that start-up tasks are now being performed on a separate thread and splash screen is displayed from the Home Screen (main) thread. In the home screen I made use of Backgroundworker to update the 'Loading...' label.
I am posting my code here hoping it may also help someone in future..
For the Home Screen code plz see the EDIT part in my question. Here's the code of Splash Screen :
public SplashScreen()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = false;
lblLoading.Text = string.Empty;
}
private void SplashScreen_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (true)
{
for (int i = 1; i <= 20; i++)
{
System.Threading.Thread.Sleep(200);
worker.ReportProgress(i);
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
string dots = string.Empty;
for (int k = 1; k <= e.ProgressPercentage; k++)
{
dots = string.Format("{0}..",dots);
}
lblLoading.Text = ("Loading" + dots);
}
You have to define a background worker in your splash screen form.
Here is an example of what your splash screen could look like :
public partial class SplashScreenForm<T> : Form
{
private BackgroundWorker _backgroundWorker;
private Func<BackgroundWorker, T> _func;
private T _funcResult;
public T FuncResult { get { return _funcResult; } }
public SplashScreenForm(Func<BackgroundWorker, T> func)
{
this._func = func;
InitializeComponent();
this.label1.Text = "";
this._backgroundWorker = new BackgroundWorker();
this._backgroundWorker.WorkerReportsProgress = true;
this._backgroundWorker.DoWork += new DoWorkEventHandler(_backgroundWorker_DoWork);
this._backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(_backgroundWorker_ProgressChanged);
this._backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_backgroundWorker_RunWorkerCompleted);
_backgroundWorker.RunWorkerAsync();
}
private void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
if (worker != null)
{
_funcResult = this._func.Invoke(worker);
}
}
private void _backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState != null)
{
this.label1.Text = e.UserState.ToString();
}
}
private void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
}
}
You can design it the way you want, maybe a pretty gif image, or whatever you can think of.
Call it this way :
private void HandleFormLoad(object sender, EventArgs e)
{
this.Hide();
var splash = new SplashScreenForm<bool>(PerformTask);
splash.ShowDialog(); // function PerformTask will be launch at this moment
this.Show();
}
private bool PerformTask(BackgroundWorker worker)
{
//...Performing tasks to be done while splash screen is displayed
worker.ReportProgress("loading..");
}
I have a .NET form with a System.Windows.Forms.Timer declared using the VS designer. The timer works fine. After I close the form, the timer doesn't fire events even if I recreate the Timer object. I've configured the Form to never close using this:
void MainFormFormClosing(object sender, FormClosingEventArgs e)
{
// never close
e.Cancel = true;
// only hide
this.Visible = false;
}
How do I make the timer fire events? What am I doing wrong?
I just tried this one. Added a WinForms Timer component on the form, start timer on load, and debug current time in debug window. Workes fine for me...
public frmTimer()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
Debug.WriteLine(DateTime.Now.ToLongTimeString());
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Visible = false;
}