There are various buttons in my form and for each button press an action is associated with it.I want to measure the time between button is pressed and released (in millisecs).How can I do it for each button.
In the Form_Load event you can iterate all buttons and dynamically attach Stopwatch to each of them, then handle their MouseDown and MouseUp events:
this.Controls.OfType<Button>().ToList().ForEach(button =>
{
button.Tag = new Stopwatch();
button.MouseDown += new MouseEventHandler(button_MouseDown);
button.MouseUp += new MouseEventHandler(button_MouseUp);
});
And the functions:
void button_MouseUp(object sender, MouseEventArgs e)
{
Stopwatch watch = ((sender as Button).Tag as Stopwatch);
watch.Stop();
MessageBox.Show("This button was clicked for " + watch.Elapsed.TotalMilliseconds + " milliseconds");
watch.Reset();
}
void button_MouseDown(object sender, MouseEventArgs e)
{
((sender as Button).Tag as Stopwatch).Start();
}
Can measure the time span using StopWatch, or use a performance profiler, like
Equatec, which has a free option too.
StopWatch relative StartNew and Stop mthods can inject, in front and at the end of the event handler.
You need to capture the KeyDown and MouseDown for the down event and the KeyUp and MouseUp for the up event.
public Form1()
{
InitializeComponent();
button1.KeyDown += new KeyEventHandler(button1_down);
button1.MouseDown+=new MouseEventHandler(button1_down);
button1.KeyUp += new KeyEventHandler(button1_Up);
button1.MouseUp += new MouseEventHandler(button1_Up);
}
void button1_down(object sender, EventArgs e)
{
Console.WriteLine(DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
}
private void button1_Up(object sender, EventArgs e)
{
Console.WriteLine(DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
}
Related
I'm trying to hold down mouse event using PreviewMouseDown and DispatcherTimer as following:
private void button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
_sec = _sec + 1;
if (_sec == 3)
{
dispatcherTimer.Stop();
MessageBox.Show(_sec.ToString());
_sec = 0;
return;
}
}
This code works, BUT the first mouse down takes 3 seconds to display the message, after that the time to show the message is decreased (less that 3 seconds)
You don't need a DispatcherTimer to do this. You could handle the PreviewMouseDown and the PreviewMouseUp events.
Please refer to the following sample code.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
PreviewMouseDown += Window3_PreviewMouseDown;
PreviewMouseUp += Window3_PreviewMouseUp;
}
DateTime mouseDown;
private void Window3_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
mouseDown = DateTime.Now;
}
readonly TimeSpan interval = TimeSpan.FromSeconds(3);
private void Window3_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
if (DateTime.Now.Subtract(mouseDown) > interval)
MessageBox.Show("Mouse was held down for > 3 seconds!");
mouseDown = DateTime.Now;
}
}
The second time this gets called
dispatcherTimer.Tick += dispatcherTimer_Tick; // try without that new EventHandler(...)
a second handled will be attached. So, after the first second, sec will be 2, since the event is called twice.
You can try to dispose and set to null the dispatcherTimer variable on the PreviewMouseUp & create a new instance on the PreviewMouseDown.
Or another option would be, on the PreviewMouseUp, you can
dispatcherTimer.Tick -= dispatcherTimer_Tick;
sec = 0;
-= will detach the event handler.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (listBox1.Items.Contains(e.KeyCode))
{
listBox1.Items.Remove(e.KeyCode);
listBox1.Refresh();
timer1.Interval -= 10;
difficultyProgessbar.Value = 800 - timer1.Interval;
stats.update(true);
}
else
{
stats.update(false);
}
correctLabel.Text = stats.correct.ToString();
missedLabel.Text = stats.missed.ToString();
totalLabel.Text = stats.total.ToString();
accuracyLabel.Text = stats.accuracy.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
//Add a random key to Listbox
listBox1.Items.Add((Keys)random.Next(65, 90));
Application.DoEvents();
if (listBox1.Items.Count > 7)
{
listBox1.Items.Clear();
listBox1.Items.Add("Game Over");
timer1.Stop();
}
}
When I run my application, timer1_Tick event is working fine, however Form1_KeyDown event doesn't execute when I press any key.
Is something missing? Why Key_Down event never fires?
Thanks
Keydown fires in the Control with Focus.
To receive it at the Form level you need to set the property. KeyPreview=True for the Form
I create following form and I click 3 buttons (randomly). After I click a button, it must show a related message after 3 seconds from clicking it. But if I had clicked another button in the meanwhile, then the related message of that button has to be shown and the previous message in the queue has to be canceled.
As an example, if I click button1 at 11.30.00, then related message should pop up only at 11.30.03 like "You clicked : 1 before 3 Seconds". But if I click another button2 before the 11.30.03, say at 11.30.02 then related message should pop up at 11.30.05 like "You clicked : 2 before 3 Seconds" and the message scheduled for 11.30.03 has to be canceled.
This is my code:
private int signal = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
signal = 1;
displayMessage(signal);
}
private void button2_Click(object sender, EventArgs e)
{
signal = 2;
displayMessage(signal);
}
private void button3_Click(object sender, EventArgs e)
{
signal = 3;
displayMessage(signal);
}
private void displayMessage(int number)
{
MessageBox.Show("You clicked : "+number+ "before 3 Seconds");
}
Set buttons Tag:
button1.Tag = 1;
button2.Tag = 2;
button3.Tag = 3;
then set Click event:
button1.Click += button_Click;
button2.Click += button_Click;
button3.Click += button_Click;
on the Click event:
private void button_Click(object sender, EventArgs e)
{
signal = (int) ((Button))sender.Tag;
displayMessage(signal);
}
Start a timer. Keep changing signal value according to button click, and when time elapsed is equal to 3 seconds, show up the messagebox from tick event. Set the timer interval according to your need and that will be reflected in the "related message".
int signal = 0;
System.Timers.Timer t = new System.Timers.Timer(3000);
private void Form1_Load(object sender, EventArgs e)
{
//----------------------- other parts of code ---------------------
// at last
t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
t.Start();
}
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (signal == 0)
return;
t.Stop();
MessageBox.Show("You clicked: " + signal + " before " + t.Interval + " Seconds");
signal = 0;
t.Start(); //move this to top of msgbox if you want timer to be reset right after poppin the msgbox.
}
private void button1_Click(object sender, EventArgs e)
{
signal = 1;
t.Stop();
t.Start();
}
private void button2_Click(object sender, EventArgs e)
{
signal = 2;
t.Stop();
t.Start();
}
private void button3_Click(object sender, EventArgs e)
{
signal = 3;
t.Stop();
t.Start();
}
This isn't a place where someone is just going to give you an answer, do some research into the area then post if you get stuck.
you want to create a static timer and check if its finished within each event
http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx
http://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.71).aspx
Here the below code enables the particular bit as high in parallel port.How to set time interval for the button click in windows form.If i set the time interval to 2 seconds the timer should start then 2 seconds after that it should stop automatically.
private void button1_Click(object sender, EventArgs e)
{
PortAccess.Output(888,1);
}
can u please let me know any suggestion or example to do this.Inside this button_click.
So you just want to clear the bit 2 seconds later? Something like this should work:
private void button1_Click(object sender, EventArgs e)
{
// Prevent multiple button clicks
button.Enabled = false;
PortAccess.Output(888, 1);
Timer timer = new Timer { Interval = 2000 };
timer.Tick += HandleTimerTick;
timer.Start();
}
private void HandleTimerTick(object sender, EventArgs e)
{
Timer timer = (Timer) sender;
timer.Stop();
timer.Dispose();
button.Enabled = true;
PortAccess.Output(888, 0);
}
You may find it simpler to set up the timer just once, and store it as an instance variable. Then you could attach the Tick event and set the interval on construction, and add it to the components of the form so that it's automatically disposed. Your methods would then be:
private void button1_Click(object sender, EventArgs e)
{
button.Enabled = false;
PortAccess.Output(888, 1);
timer.Start();
}
private void HandleTimerTick(object sender, EventArgs e)
{
timer.Stop();
button.Enabled = true;
PortAccess.Output(888, 0);
}
Made a simple app which using a timer, counts the number of mouse clicks on a panel for a given duration... simple enough, all working, except it seems to fail to count quickly enough to register all the mouse clicks?
I am literally incrementing a private int value on the click event of the panel, and showing a message box with the results on tick. Any Ideas? Code below...
Matt.
public partial class Form1 : Form
{
int click = 0;
public Form1()
{
InitializeComponent();
}
private void panel1_Click(object sender, EventArgs e)
{
click++;
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void btnReset_Click(object sender, EventArgs e)
{
timer1.Stop();
txtClicks.Text = "";
txtTime.Text = "";
click = 0;
}
private void btnGo_Click(object sender, EventArgs e)
{
click = 0;
timer1.Interval = int.Parse(txtTime.Text) * 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
MessageBox.Show(txtClicks.Text + " seconds up, No of clicks:" + click.ToString());
}
}
Use the MouseDown Event. That'll handle every time and negate the need to handle both Click and DoubleClick.
except it seems to fail to count quickly enough to register all the mouse clicks?
may be you should handle Mouse DoubleClick event as well as Mouse Click?
I would put money on it that some of the clicks are coming through so fast that...... they count as a double click.
If you add a double click handler, and increment the counter twice while in that handler, does it produce a more accurate result?