Perform an action when a timer elapses [duplicate] - c#

This question already has an answer here:
how to display a message box when timer elapses in c#
(1 answer)
Closed 8 years ago.
I want to provide a beep sound to indicate that my timer is elapsed. Where would I put the code such that it happens when my timer has expired?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
Timer aTimer = new Timer();
aTimer.Interval = 1000;
// Hook up the Elapsed event for the timer.
aTimer.Enabled = true;
aTimer.tick += OnTimedEvent;
}
private void OnTimedEvent(object sender, EventArgs e)
{
MessageBox.Show("process");
}

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.Media;
namespace delete
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Enabled = true;
timer1.Interval = 1000;
}
private void timer1_Tick(object sender, EventArgs e)
{
SoundPlayer sp = new SoundPlayer();
sp.Play();
}
}
}
don't forget to add using System.Media;

Related

How can I use invoke for fixing exception error?

I am trying to write a code for taking fps at label while taking view from the camera.
So, I used task for that and I used timer but I got an error. I fixed the problem with using CheckForIllegalCrossThreadCalls = false; but as far as I know it is not an effective way.
I want to fix this with using invoke. How should I write the code properly?
Here is the code:
using System;
using System.Drawing;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace projectimg
{
public partial class Form1 : Form
{
Stopwatch watch = new Stopwatch();
System.Timers.Timer timerFPS;
public Form1()
{
InitializeComponent();
}
CameraConnection connnection;
private bool btn_GetviewWasClicked = false;
private void Form1_Load(object sender, EventArgs e)
{
btn_Getview.Click += Btn_Getview_Click;
timerFPS = new System.Timers.Timer(1000);
timerFPS.Elapsed += TimerFPS_Elapsed;
timerFPS.Start();
}
private void Btn_Getview_Click(object sender, EventArgs e)
{
btn_GetviewWasClicked = true;
Task.Run(() =>
{
connnection = new CameraConnection();
connnection.Connect();
});
CameraConnection.DataReceived += CameraConnection_DataReceived;
}
private void TimerFPS_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
txt_fps.Text = Convert.ToString(CameraConnection.count);
CameraConnection.count = 0;
}
}
}

When using SendKeys.SendWait in backgroundworker why I can hear ever 3 seconds kind of beep?

Like the form1 maybe not in focus when it's doing the SendKeys ?
The main goal in the end will be to simulate key press combination Ctrl+S when a specific process window is in the front in a focus.
The problem is when the process window is in the front now and I'm using it's menu there are beeps each time the timer send keys like the Form1 or the process I'm using it's menu are not in focus. Not sure.
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 Process_Window
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
worker.DoWork += Worker_DoWork;
worker.ProgressChanged += Worker_ProgressChanged;
worker.RunWorkerCompleted += Worker_RunWorkerCompleted; ;
worker.RunWorkerAsync();
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
SendKeys.SendWait("^s");
}
private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
}
}
SetForeGroundWindow
You could use this just before calling SendKeys.SendWait() so you're quite sure you sent Ctrl+S to the good window, you can use SetForeGroundWindow with FindWindow if i remember the name correctly.

timer1_Tick event in WinForms C# in presence of axWindowsMediaPlayer

Note: This application will be designed for a touch device (MS Surface Hub)
My Windows Form contains axWindowsMediaPlayer component. I have created a playlist and I am able to loop the media files in the playlist. However, I want my axWindowsMediaPlayer playlist to pause after 5 sec (time limit just for testing/debugging purpose) of inactivity (No input from the user to be more precise) and display a dialog-box asking me whether I wish to continue.
Following is my code to set a timer_Tick event:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TimerDemo
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
public static extern Boolean GetLastInputInfo(ref tagLASTINPUTINFO plii);
public struct tagLASTINPUTINFO
{
public uint cbSize;
public Int32 dwTime;
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
axWindowsMediaPlayer1.Ctlenabled = true;
var pl = axWindowsMediaPlayer1.playlistCollection.newPlaylist("MyPlaylist");
pl.appendItem(axWindowsMediaPlayer1.newMedia(#"C:\ABC\abc1.mp4"));
pl.appendItem(axWindowsMediaPlayer1.newMedia(#"C:\ABC\abc2.mp4"));
axWindowsMediaPlayer1.currentPlaylist = pl;
axWindowsMediaPlayer1.Ctlcontrols.play();
}
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (e.newState == 8) //Media Ended
{
}
}
private void timer1_Tick(object sender, EventArgs e)
{
tagLASTINPUTINFO LastInput = new tagLASTINPUTINFO();
Int32 IdleTime;
LastInput.cbSize = (uint)Marshal.SizeOf(LastInput);
LastInput.dwTime = 0;
if (GetLastInputInfo(ref LastInput))
{
IdleTime = System.Environment.TickCount - LastInput.dwTime;
if (IdleTime > 5000)
{
axWindowsMediaPlayer1.Ctlcontrols.pause();
timer1.Stop();
MessageBox.Show("Do you wish to continue?");
}
else
{
}
timer1.Start();
axWindowsMediaPlayer1.Ctlcontrols.play();
}
}
}
}
With this code, the application is not entering the timer1_Tick Event.
Queries:
Does e.newState == 3 (Playing State) in axWindowsMediaPlayer considered as input?
How do I ensure that the application enters into timer1_Tick event?
If I remove the axWindowsMediaPlayer part of the code then the timer1_Tick event is responding.
For your application to get into the timer_Tick event, you first need to start the timer.
Replace the following code:
public Form1()
{
InitializeComponent();
}
With the Following:
public Form1()
{
InitializeComponent();
timer1.Start();
}
This should work fine for you.

is there a way to stop a timer on visual studios at a certain point instead of it keep going

basically I mean I want a picture to move when I press a button and the picture to sop moving at a certain point on the form application, not cancel it the picture to move then just stop with the application still running. on Microsoft visual studios c# windows form application
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
pictureBox1.Left += 2;
}
}
}
You can call timer1.Stop() to stop the timer.
You need to set the Interval property of the timer to raise the TickEvent once after that Interval is Elapsed.
In TickEvent you can Stop the Timer or do whatever you want to do.
Try This :
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval=5000;//to raise tick event for 5 sec's
timer1.Start();
timer1.Tick += new System.EventHandler(this.timer1_Tick);
}
protected void timer1_Tick(Object sender,EventArgs e)
{
//Stop the timer here
timer1.Stop();
}

How can I multithread (effectively) on Windows Forms?

This one is giving me a hard time.
The thing is that I have a code that plays some notes in MIDI, and I wanted to be able to pause it, so I made a simple Form like this:
namespace Music
{
public partial class Form1 : Form
{
static BackgroundWorker _bw = new BackgroundWorker
{
WorkerSupportsCancellation = true
};
private void button1_Click(object sender, EventArgs e)
{
if (!Playing)
{
Playing = true;
_bw.DoWork += Start_Playing;
_bw.RunWorkerAsync("Hello to worker");
}
else
{
Playing = false;
_bw.CancelAsync();
}
}
static void Start_Playing(object sender, DoWorkEventArgs e)
{
//Plays some music
}
}
}
And when I click it starts playing, but no matter what I do, it can't stop. But the thing is that if I do the same thing in the console it works perfect.
Did I miss something?
How can I control a separate thread from the form?
This seems to work...
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.Threading;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private BackgroundWorker _bw = new BackgroundWorker { WorkerSupportsCancellation = true,
WorkerReportsProgress = true};
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (_bw.IsBusy)
{
_bw.CancelAsync();
}
else
{
_bw.ProgressChanged += new ProgressChangedEventHandler(_bw_ProgressChanged);
_bw.DoWork += new DoWorkEventHandler(_bw_DoWork);
_bw.RunWorkerAsync();
}
}
void _bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
textBox1.Text += (string)e.UserState;
}
void _bw_DoWork(object sender, DoWorkEventArgs e)
{
int count = 0;
while (!_bw.CancellationPending)
{
_bw.ReportProgress(0, string.Format("worker working {0}", count));
++count;
Thread.Sleep(2000);
}
}
}
}

Categories