C# Timer not stopping? - c#

Here's what I have, why is my timer(s) not stopping?
I'm not sure what I'm doing wrong.
I'm fairly new to C# and I'm trying to make it so my splash screen Hides(form1) and my program starts(samptool) however my program starts but the splash screen stays and the timers reset instead of stopping. Every 6.5 seconds the application opens in a new window.
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;
using System.Timers;
namespace SplashScreen.cs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Interval = 250;
timer2.Interval = 6500;
timer1.Start();
timer2.Start();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
this.progressBar1.Increment(5);
}
private void timer2_Tick(object sender, EventArgs e)
{
SampTool w = new SampTool();
Form1 m = new Form1();
timer1.Enabled = false;
timer1.Stop();
timer2.Enabled = false;
timer2.Stop();
m.Hide();
w.Show();
}
}
}

When you use the new keyword, you create a new instance of a class:
Form1 m = new Form1();
When you create a new instance, the constructor is invoked (the constructor is the method that is named the same as the class).
This will run all the code in the constructor again, hence creating new timers.
To close the current form, you should just run the forms Hide method:
private void timer2_Tick(object sender, EventArgs e)
{
timer1.Stop();
timer2.Stop();
SampTool sampTool = new SampTool();
sampTool.Show();
Hide(); // call the Forms Hide function.
}

Related

How to hide multiple forms with one click in Visual Studio?

I have a form named: form1 from which I can access two other forms: form2 and form3, with one click:
private void buttonViewEmployee_Click(object sender, EventArgs e)
{
string refNumber = 123;
Employee employee = new Employee(refNumber);
FormViewEmployee viewEmployee = new FormViewEmployee(employee);
FormViewNewUpdates newUpdates = new FormViewNewUpdates(employee);
viewEmployee.Show();
newUpdates.Show();
this.Hide();
}
Now, from form3 I would like to hide form2 and form3 and go back to form1:
private void buttonBack_Click(object sender, EventArgs e)
{
FormEditRequests editRequest = new FormEditRequests();
FormViewEmployee viewEmp = new FormViewEmployee(null);
viewEmp.Hide();
this.Hide();
editRequest.Show();
}
It seems to work but form2 actually just hides itself behind form1 but is still visible.
I tried to debug to see what happens exactly but when I debug, it works as perfect as I want but not when I am not debugging.
I tried to change the order of the code execution and also tried to use:
private void Form1_Load(object sender, EventArgs e)
{
FormViewEmployee viewEmp = new FormViewEmployee(null);
base.OnVisibleChanged(e);
viewEmp.Visible = false;
}
But didn't work either.
Can someone explains what happens during the debug mode that doesn't happen when not debugging?
Try following code:
public static void closeAllOpenedForms()
{
FormCollection FM = Application.OpenForms;
if (FM.Count > 1)
{
for (int i = (FM.Count); i > 1; i--)
{
Form sForm = Application.OpenForms[i - 1];
sForm.Close();
}
}
}
You can check/clone/test this code on https://github.com/JomaStackOverflowAnswers/HideForms
If you need to reuse the opened form you can hide/show as neeeded. But if you create new forms everytime is recommended to close the forms(not hide).
FormMain
namespace HideForms
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void buttonOpen_Click(object sender, EventArgs e)
{
Employee employee = new Employee("123");
FormViewEmployee formViewEmployee = new FormViewEmployee(employee);
FormViewNewUpdates formViewNewUpdates = new FormViewNewUpdates(employee, this, new List<Form>{ formViewEmployee });
formViewEmployee.Show();
formViewNewUpdates.Show();
Hide();
}
}
}
FormViewEmployee
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 HideForms
{
public partial class FormViewEmployee : Form
{
private readonly Employee employee;
public FormViewEmployee(Employee employee)
{
InitializeComponent();
this.employee = employee;
}
}
}
FormViewNewUpdates
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 HideForms
{
public partial class FormViewNewUpdates : Form
{
private readonly Employee employee;
private readonly Form parent;
private readonly List<Form> formsToClose;
public FormViewNewUpdates(Employee employee, Form parent, List<Form> formsToClose)
{
InitializeComponent();
this.employee = employee;
this.parent = parent;
this.formsToClose = formsToClose;
}
private void buttonClose_Click(object sender, EventArgs e)
{
foreach(var form in formsToClose)
{
form.Close();//form.Hide(); //Hide in case you need to reuse the form.
}
Close();
parent.Show();// Show the parent form.
}
private void FormViewNewUpdates_FormClosing(object sender, FormClosingEventArgs e)
{
foreach (var form in formsToClose)
{
form.Close();
}
parent.Show();
}
}
}
Output
FormMain When click in open button, it opens FormViewEmployee, FormViewNewUpdates instances.
FormViewEmployee, FormViewNewUpdates instances
When click in Close All button it close both instances and show FormMain instance.
2
References
Control.Hide
Form.Close

Auto shuffle between windows forms every after 5 min

Experts
I would like to shuffle windows forms automatically every after 5 mins. windows forms contains Multiple querys , Multiple videos, Multiple powerpoints.
I am having three windows forms, as follows.
Forms 1 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;
namespace Daily_System {
public partial class Form1: Form {
public Form1() {
InitializeComponent();
timer1.Enabled = true;
timer1.Interval = 5000;
timer1.Tick += timer1_Tick;
timer1.Start();
}
private void Form1_Load(object sender, EventArgs e) {
this.WindowState = FormWindowState.Maximized;
CenterToScreen();
}
private Timer timer1 = new Timer();
private void button1_Click_1(object sender, EventArgs e) {
this.WindowState = FormWindowState.Minimized;
Form2 f = new Form2(); // This is bad
timer2.Enabled = true;
}
private void timer2_Tick(object sender, EventArgs e) {
button1.PerformClick();
}
}
}
Forms 2: Microsoft Powerpoint file
multiple powerpoint files from network folder(path)
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 PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Core = Microsoft.Office.Core;
namespace Daily_System {
public partial class Form2: Form {
public Form2() {
InitializeComponent();
this.WindowState = FormWindowState.Minimized;
timer1.Enabled = true;
timer1.Interval = 15000;
timer1.Start();
}
private void Tick(object sender, EventArgs e) {
Form3 Next = new Form3();
Next.Show();
this.Hide();
timer1.Stop(); //Stop timer after tick once
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.BeginInvoke(new MethodInvoker(delegate() {
button1.PerformClick();
}));
}
private void button1_Click(object sender, EventArgs e) {
Microsoft.Office.Interop.PowerPoint.Application pptApp = new Microsoft.Office.Interop.PowerPoint.Application();
Microsoft.Office.Core.MsoTriState ofalse = Microsoft.Office.Core.MsoTriState.msoFalse;
Microsoft.Office.Core.MsoTriState otrue = Microsoft.Office.Core.MsoTriState.msoTrue;
pptApp.Visible = otrue;
pptApp.Activate();
Microsoft.Office.Interop.PowerPoint.Presentations ps = pptApp.Presentations;
var opApp = new Microsoft.Office.Interop.PowerPoint.Application();
pptApp.SlideShowEnd += PpApp_SlideShowEnd;
var ppPresentation = ps.Open(# "C:\Users\ok\Downloads\Parks-WASD2017.pptx", ofalse, ofalse, otrue);
var settings = ppPresentation.SlideShowSettings;
settings.Run();
}
private void PpApp_SlideShowEnd(Microsoft.Office.Interop.PowerPoint.Presentation Pres) {
Pres.Saved = Microsoft.Office.Core.MsoTriState.msoTrue;
Pres.Close();
}
private void Form2_Load(object sender, EventArgs e) {
}
private void button2_Click(object sender, EventArgs e) {
this.WindowState = FormWindowState.Minimized;
Form3 f = new Form3(); // This is bad
f.Show(); /// f.Show();
timer1.Enabled = true;
this.Hide();
timer1.Stop(); //Stop timer after tick once
}
private void timer1_Tick_1(object sender, EventArgs e) {
button2.PerformClick();
}
}
}
Forms 3: Multiple video files (MP4,FLV,MOV,etc)
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 Daily_System {
public partial class Form3: Form {
public Form3() {
InitializeComponent();
timer1.Enabled = true;
timer1.Interval = 15000;
timer1.Start();
}
private void Form3_Load(object sender, EventArgs e) {
axWindowsMediaPlayer1.settings.autoStart = true;
}
private void axWindowsMediaPlayer1_Enter_1(object sender, EventArgs e) {
axWindowsMediaPlayer1.URL = # "C:\Users\ok\Downloads\ok.mp4";
}
private void button1_Click(object sender, EventArgs e) {
this.WindowState = FormWindowState.Minimized;
Form1 f = new Form1(); // This is bad
f.Show(); /// f.Show();
timer1.Enabled = true;
this.Hide();
timer1.Stop(); //Stop timer after tick once
}
private void timer1_Tick_1(object sender, EventArgs e) {
button1.PerformClick();
}
}
}
Multiple video files from network folder(Path)
Requirement:
Each forms should change and display every after 5 min.
example : first form1 should display then after 5 mins form1 should minimized and form2 should show the slideshow and then after 5 mins form2 should minimized and form3 should play the video and then after 5 mins form3 should minimized and pause the video then form1 should display.
It should keep doing the same steps as above.
Final condition: All forms should stop exactly at 6 pm(Everyday) and it should start automatically at 7 am (Everyday).
Please advise...
One way is to create base class for forms to control minimizing and maximizing of them and also finding out when the specific form being minimized or maximized by overriding OnStart() and OnStop() methods. This can be done as follow:
Define new base class named CustomForm:
public class CustomForm : Form
{
public static List<CustomForm> AllForms = new List<CustomForm>();
private static int CurrentFormIndex = 0;
private static Timer SliderTimer = new Timer() { Interval = 5000 }; // { Interval = 5 * 60000 };
public static void Start(params CustomForm[] forms)
{
AllForms.AddRange(forms);
forms[0].Show();
forms[0].WindowState = FormWindowState.Maximized;
AllForms[0].OnStart(AllForms[0]);
SliderTimer.Tick += SliderTimer_Tick;
SliderTimer.Start();
}
private static void SliderTimer_Tick(object sender, EventArgs e)
{
SliderTimer.Stop();
// Minimizing current form
AllForms[CurrentFormIndex].OnStop(AllForms[CurrentFormIndex]);
AllForms[CurrentFormIndex].WindowState = FormWindowState.Minimized;
// Maximizing next form
int NextFormIndex = (CurrentFormIndex + 1) % AllForms.Count;
if (!AllForms[NextFormIndex].Visible)
AllForms[NextFormIndex].Show();
AllForms[NextFormIndex].WindowState = FormWindowState.Maximized;
AllForms[NextFormIndex].OnStart(AllForms[NextFormIndex]);
CurrentFormIndex = NextFormIndex;
SliderTimer.Start();
}
// Application will exits when one of forms being closed
protected override void OnFormClosed(FormClosedEventArgs e)
{
base.OnFormClosed(e);
Application.Exit();
}
// For overriding in forms to Start something such as playing or etc
protected virtual void OnStart(CustomForm Sender)
{
}
// For overriding in forms to Stop something such as playing or etc
protected virtual void OnStop(CustomForm Sender)
{
}
}
Change Program class as follow:
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
CustomForm.Start(new Form1(), new Form2(), new Form3());
Application.Run();
}
}
Change your forms to inherit CustomForm instead of Form as follow:
public partial class Form1 : CustomForm
{
public Form1()
{
InitializeComponent();
}
private void Form1_Shown(object sender, EventArgs e)
{
// axWindowsMediaPlayer1.URL = #"C:\Users\ok\Downloads\ok.mp4";
WMPLib.IWMPMedia v1 = axWindowsMediaPlayer1.newMedia(#"d:\1.mp4");
axWindowsMediaPlayer1.currentPlaylist.appendItem(v1);
WMPLib.IWMPMedia v2 = axWindowsMediaPlayer1.newMedia(#"d:\2.mp4");
axWindowsMediaPlayer1.currentPlaylist.appendItem(v2);
WMPLib.IWMPMedia v3 = axWindowsMediaPlayer1.newMedia(#"d:\3.mp4");
axWindowsMediaPlayer1.currentPlaylist.appendItem(v3);
}
// To start playing video and etc when form being maximized
protected override void OnStart(CustomForm Sender)
{
axWindowsMediaPlayer1.Ctlcontrols.play();
}
// To stop playing video and etc when form being minimized
protected override void OnStop(CustomForm Sender)
{
axWindowsMediaPlayer1.Ctlcontrols.pause();
}
}
Form2:
public partial class Form2 : CustomForm
{
Microsoft.Office.Interop.PowerPoint.Presentation ppPresentation;
Microsoft.Office.Interop.PowerPoint.SlideShowSettings settings;
Microsoft.Office.Interop.PowerPoint.Application opApp;
int StartingSlide = 1;
public Form2()
{
InitializeComponent();
}
protected override void OnStart(CustomForm Sender)
{
Microsoft.Office.Interop.PowerPoint.Application pptApp = new Microsoft.Office.Interop.PowerPoint.Application();
Microsoft.Office.Core.MsoTriState ofalse = Microsoft.Office.Core.MsoTriState.msoFalse;
Microsoft.Office.Core.MsoTriState otrue = Microsoft.Office.Core.MsoTriState.msoTrue;
pptApp.Visible = otrue;
pptApp.Activate();
Microsoft.Office.Interop.PowerPoint.Presentations ps = pptApp.Presentations;
opApp = new Microsoft.Office.Interop.PowerPoint.Application();
opApp.SlideShowNextSlide += OpApp_SlideShowNextSlide;
ppPresentation = ps.Open(#"c:\a.pptx", ofalse, ofalse, otrue);
settings = ppPresentation.SlideShowSettings;
settings.RangeType = Microsoft.Office.Interop.PowerPoint.PpSlideShowRangeType.ppShowSlideRange;
settings.StartingSlide = StartingSlide;
settings.Run();
}
private void OpApp_SlideShowNextSlide(Microsoft.Office.Interop.PowerPoint.SlideShowWindow Wn)
{
StartingSlide = Wn.View.CurrentShowPosition;
}
protected override void OnStop(CustomForm Sender)
{
ppPresentation.Close();
//opApp.Quit();
Process.Start("cmd", "/c taskkill /im POWERPNT.EXE");
}
}
There are a lot of possible ways to do this. Winforms is a Lego box and lets you snap the pieces together any way you want. Deriving your own class from one of the built-in winforms classes is a basic strategy. What you need is a little controller that takes care of the form switching. Best kind of class to override is ApplicationContext. The default one you get is a very simple one that merely ensures that the main form is shown and terminates the app when you close it.
Let's derive our own. This is a potentially heavy-weight app, these are not cheap forms. So we want to specify the forms to switch by their Type instead of their instance, creating and destroying them when the forms gets switched. You'll want the app to terminate whenever the current one is closed by the user. Copy/paste this code into the Program.cs file:
class FormSwitcher : ApplicationContext {
Timer switcher;
Type[] forms;
int formIndex;
Form currentForm;
bool switching;
public FormSwitcher(params Type[] forms) {
this.forms = forms;
switcher = new Timer() { Enabled = true };
switcher.Interval = System.Diagnostics.Debugger.IsAttached ? 3000 : 5 * 60000;
switcher.Tick += SwitchForm;
formIndex = -1;
SwitchForm(this, EventArgs.Empty);
}
private void SwitchForm(object sender, EventArgs e) {
switching = true;
formIndex += 1;
if (formIndex >= forms.Length) formIndex = 0;
var newform = (Form)Activator.CreateInstance(forms[formIndex]);
newform.FormClosed += delegate { if (!switching) this.ExitThread(); };
if (currentForm != null) {
newform.StartPosition = FormStartPosition.Manual;
newform.Bounds = currentForm.Bounds;
}
newform.Show();
if (currentForm != null) currentForm.Close();
currentForm = newform;
switching = false;
}
}
Hopefully it is obvious what it does, if not then let me know and I'll add comments. Now you can modify the Main() method in that same file, you pass an instance of this class to the Application.Run() method. I'll copy/paste the code I tested:
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormSwitcher(typeof(Form1), typeof(Form2)));
}
Here is sample code that creates the 3 forms, then every 5 seconds switches which is maximized (others are minimized). The application exits when any form is closed. I've put comments throughout, and following it is code you can use to pause playback on forms:
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//here we create our 3 forms. note, you can create and show as many as you want here
//the application will automatically loop through them
new Form1().Show();
new Form2().Show();
new Form().Show();
//minimize all forms, and set a close handler
foreach (Form form in Application.OpenForms)
{
form.WindowState = FormWindowState.Minimized;
form.FormClosed += Form_FormClosed;
}
//start a thread to manage switching them
Task.Run((Action)Go);
//start the main UI thread loop
Application.Run();
}
private static void Go()
{
while (true)
{
//loop through all forms
foreach (Form form in Application.OpenForms)
{
//show it (send execution to UI thread)
form.Invoke(new MethodInvoker(() =>
{
form.Show();
form.WindowState = FormWindowState.Maximized;
}));
//wait 5 seconds
Thread.Sleep(5000);
//minimize it (send execution to UI thread)
form.Invoke(new MethodInvoker(() =>
{
form.WindowState = FormWindowState.Minimized;
}));
}
}
}
private static void Form_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
Now for forms that need to take action when minimized/maximized, add a Resize handler like this into the code on the form:
private void Form1_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
//stop any playback
} else
{
//start any playback
}
}

Button that close from 1 and opens form 2 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
so what i want is when you press the button you open form 2 where my game is. the button wich is at form 1 is going to be my main menu for the game, you click it and it opens the game and closes the menu (if it is possible to do this with out having 2 forms and just using 1 do share how i can do this)
Form 1
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 WindowsFormsApplication3
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
Form 2
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 Spill
{
public partial class MainWindow : Form
{
Random _random;
public MainWindow()
{
InitializeComponent();
_random = new Random();
}
private void MainWindow_Load(object sender, EventArgs e)
{
Size s = new System.Drawing.Size(800, 600);
this.ClientSize = s;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
}
private void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
{
if (e.KeyCode == Keys.Left)
{
Player.Left -= 20;
}
if (e.KeyCode == Keys.Right)
{
Player.Left += 20;
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
int z = _random.Next(0, 10);
int x = _random.Next(0, 20);
int y = _random.Next(0, 30);
LargeEnemy.Left += z;
MediumEnemy.Left += x;
SmallEnemy.Left += y;
}
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Restart();
}
private void quitGameToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void LargeEnemy_Click(object sender, EventArgs e)
{
}
}
}
It's very simple:
using System;
using System.Collections.Generic;
using System.ComponentModel;
System.Data;
System.Drawing;
using System.Linq;
System.Text;
System.Threading.Tasks;
System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//hide the current winform
this.Hide();
//create game winform
WindowsFormsApplication1 frmGame = new WindowsFormsApplication1();
//show the game winform
frmGame.ShowDialog();
//when the game winform closes show again the menu
this.Show();
}
}
}
and in the second form in this functions set them like this
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void quitGameToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
This is a very simple example using a form manager to handle a single instance. This way both forms stay live and you are just updating the visibility.
You will want to close both forms correctly to close the application.
namespace WindowsFormsApplication1
{
static class FormManager
{
public static Form1 Game = new Form1();
public static Form2 Menu = new Form2();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(FormManager.Game);
}
public partial class Form1 : Form
{
private void btn_Menu_Click(object sender, EventArgs e)
{
FormManager.Game.Hide();
FormManager.Menu.Show();
}
}
public partial class Form2 : Form
{
private void btn_Close_Click(object sender, EventArgs e)
{
FormManager.Menu.Hide();
FormManager.Game.Show();
}
}
}

Visual Studio C# while loop freezing forms application [duplicate]

This question already has answers here:
Thread.Sleep() in C#
(4 answers)
Closed 6 years ago.
Here's 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 _8BB_2._0
{
public partial class Form1 : Form
{
public static class globalVars
{
public static bool spacerunning = false;
}
public Form1()
{
InitializeComponent();
globalVars.spacerunning = false;
}
private void button1_Click(object sender, EventArgs e)
{
if (!globalVars.spacerunning)
{
globalVars.spacerunning = true;
while (globalVars.spacerunning)
{
Thread.Sleep(1000);
SendKeys.Send(" ");
}
}
else if (globalVars.spacerunning)
{
globalVars.spacerunning = false;
}
}
}
}
When I click button1 it's starts hitting space every second like it should but when I try to click it again to shut it off the application freezes and it keeps pressing space. I've tried multiple other ways but can't seem to figure out how I can do two things at once since I get locked inside of the while loop.
Calling Thread.Sleep() will block the UI thread. Try to use async/await instead.
private async void button1_Click(object sender, EventArgs e)
{
globalVars.spacerunning = !globalVars.spacerunning;
while (globalVars.spacerunning)
{
await Task.Delay(1000);
SendKeys.Send(" ");
}
}
UPDATE:
You may use a Timer instead.
public class MainForm : Form
{
private Timer timer = new Timer() { Interval = 1000 };
public MainForm()
{
/* other initializations */
timer.Enabled = false;
timer.Tick += timer_Tick;
}
private void timer_Tick(object sender, EventArgs e)
{
SendKeys.Send(" ");
}
private void button1_Click(object sender, EventArgs e)
{
globalVars.spacerunning = !globalVars.spacerunning;
timer.Enabled = globalVars.spacerunning;
}
}

How can I interrupt playing of text to speech synthesis in my application?

This is the code that I used to speech a richTextBox. My problem is that I can't click on anything when the text is playing. I can't even stop playing. How can I fix the problem? Is there any way to stop playing by clicking on a button?
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;
using System.Speech.Synthesis;
namespace Merger
{
public partial class Form1 : Form
{
SpeechSynthesizer tell = new SpeechSynthesizer();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
richTextBox1.SelectionAlignment = HorizontalAlignment.Center;
tell.Rate = trackBar1.Value;
}
private void Form1_Resize(object sender, EventArgs e)
{
this.Refresh();
}
private void pictureBox2_Click(object sender, EventArgs e)
{
tell.Volume = 100;
tell.Speak(richTextBox1.SelectedText);
}
private void trackBar1_ValueChanged(object sender, EventArgs e)
{
tell.Rate = trackBar1.Value;
}
private void button1_Click(object sender, EventArgs e)
{
tell.SpeakAsyncCancelAll();
}
}
}
The problem is that the Speak() method is Synchronous, so it will lock the thread you're on. Assuming you're on a single thread, that will be the UI thread, thus locking anything you're doing.
You might perhaps be better using a different thread to Speak(), which won't lock your current (UI) thread.
SpeechSynthesizer.Speak Method (String) - MSDN
Or you can use the SpeechAsync method, which will do it asyncronously!
SpeechSynthesizer.SpeakAsync Method (String) - MSDN

Categories

Resources