How to catch event Mouse Hold on a control? - c#

I want to catch the event that user clicks and holds mouse on a control in C#.
I have read on MSDN and I only see events Mouse Down, Mouse Up, ... but don't have Move Hold event.

You need to use mentinoed events with some timer between them.
Example:
MouseDown
Start Timer
MouseUp
Disable Timer
In case if user holds more then timer time - invoke your event handler, when mouseUp happend faster then timer elapsed - disable runned timer.

First, you should use stop watch to detect time you want.
using System.Diagnostics;
Second, define a global instance of stopwatch class.
Stopwatch s = new Stopwatch();
This is the first event you should use:
private void controlName_MouseDown(object sender, MouseEventArgs e)
{
s.Start();
}
This is the second event you should use:
private void controlName_MouseUp(object sender, MouseEventArgs e)
{
s.Stop();
//determine time you want . but take attention it's in millisecond
if (s.ElapsedMilliseconds <= 700 && s.ElapsedMilliseconds >= 200)
{
//you code here.
}
s.Reset();
}

Related

Long Press Detector with c# in xamarin.forms

I am making a simple calculator app where the DEL button removes the last digit in the viewport, but if held down for one second it deletes everything in the viewport. Right now If I press the button once, it deletes the last digit whether I hold it down or not. If I press it down again (held down or just a regular tap) it clears everything in the viewport and I cannot type anything else in.
Firstly I create the timer like so:
public System.Timers.Timer timer = new System.Timers.Timer(1);
and then I have a function for when the 'DEL' button is pressed:
private void DeletePressed(object sender, EventArgs args)
{
timer.Stop();
timer.Start();
timer.Elapsed += AllClear;
}
a function to stop the timer and delete the last character from the viewport when the button is released:
private void DeleteReleased(object sender, EventArgs args)
{
timer.Stop();
if (CalculatorString.Length > 0)
{
CalculatorString = CalculatorString.Remove(CalculatorString.Length - 1);
}
viewport.Text = CalculatorString;
}
and finally the procedure that is called when the timer finishes:
private void AllClear(Object Source, System.Timers.ElapsedEventArgs e)
{
timer.Stop();
CalculatorString = "";
viewport.Text = CalculatorString;
}
however none of what I expected tohas happened. I appreciate any help in advance :)
There is no direct way to listen long press in Xamarin.Forms(PCL). You have to write separate custom renderers for each platform to Listen long press and communicate it to the PCL.
You can refer this link for code example for doing the same.

MouseHook, MouseDown and MouseClick split

I have a little problem. I tried to look at google, but it gave me nothing much.
I made a little program that uses global hooks and get mouse coordinates on click. The problem is when I made a second method with MouseDown and when I just click a button, MouseDown method runs too.
So the question is:
How can I split two methods and let them work only separately: when I click, only MouseClick method is triggered, when press and keep down for a while it triggers only MouseDown?
Should I use some timing or what? Just give me a tip what I should try to use.
P.S. Sorry, my English isn't good, it's not my native language.
Here is some code, that I think give the overview.
public void StartRecording()
{
mouseListener = new MouseHookListener(new GlobalHooker());
mouseListener.Start();
mouseListener.MouseClick += new MouseEventHandler(MouseClicked);
mouseListener.MouseDown += new MouseEventHandler(MouseDown);
}
public void MouseClicked(object sender, MouseEventArgs e)
{
MessageBox.Show(String.Format("Mouse was pressed at {0}, {1}",
Control.MousePosition.X.ToString(),
Control.MousePosition.Y.ToString()));
}
public void MouseDown(object sender, MouseEventArgs e)
{
MessageBox.Show(String.Format("Mouse was down at {0}, {1}",
Control.MousePosition.X.ToString(),
Control.MousePosition.Y.ToString()));
}
When you click the mouse both is the case.
MouseClick is as far as i know both MouseDown and MouseUp, where MouseDown will be fired when you press down. And MouseUp will be fired when you release the button..
I think you will have to add some functionality to the MouseDown method which counts how long the mouse was pressed down.. That would be my solution.
In the MouseDown event you should store the current time and coordinates in variables that are global to the class they are in.
Then, you should use the MouseUp event to detect when the mouse button is released. You can then compare the new time and coordinates to the stored ones to see how long the button was pressed and if the mouse moved in that time, and act upon it accordingly.
Alternatively, you could also use the MouseMove event to reset the time and coordinates if required.
As a workaround, instead of hooking to MouseClick, try using MouseUp.
Then on MouseDown save current time in a class level variable (clickTime in the example). On MouseUp check the time again. If the time span is longer then say 3 seconds - do what you wanted to do on mouse down, otherwise - continue with mouse click.
DateTime clickTime;
public void MouseUp(object sender, MouseEventArgs e)
{
if (DateTime.Now - clickTime > someDelayTime)
{
// Do mouse down
}
else
{
// Do mouse click
}
}
public void MouseDown(object sender, MouseEventArgs e)
{
clickTime = DateTime.Now;
}

How to use Key Event in Timer?

I have the following code, which on key press, starts moving the two labels from top of the form to the bottom, and after reaching the bottom of the form, it stops. I have done it using the timer. Here is the code
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
label1.Text = "Key Pressed: " + e.KeyChar;
//animate(sender, e);
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
Random random = new Random();
int X = random.Next(0, 1230);
int y = X;
label2.Location = new Point(X, 5);
label3.Location = new Point(X + 20, 5 + 20);
for (int i = 5; i <= 470; i++)
{
label2.Location = new Point(y, i);
label3.Location = new Point(y + 20, i + 20);
Thread.Sleep(1);
}
timer1.Stop();
}
Now during the animation (from the top of the form to the bottom), when I press the key, the animation restarts after reaching the bottom i.e. it completes the tick event and then and only then starts over or stop.
Now what I want is that whenever, during this movement of the labels from the top to bottom i.e. during the tick, if I press any key (or any specific key), the timer should stop.
In short, during the Timer1_Tick method, I want it to stop immediately on a key press.
I tried but couldn't get it to work. I hope that you folks here would help me sort this issue out and hope that you reply on your earliest. Thank you for your time!
The problem here is that you are not really using the Timer in the way that it's intended to be used. Ideally you would have an event that makes a change every time the tick event fires for a Timer.
Here you listen to the event and do several rounds of processing without ever returning from the handler at which point you stop the timer. This means the code will only ever process the tick event once instead of N times.
To fix this try breaking up the handler to do incremental work once per tick and only stop once the drawing is complete. This will also allow you to handle key events in between the tick events and stop the timer. The best place to break up the work is at the Thread.Sleep call (which itself should not appear in the handler)
Try it is so simple
Public Boolean tick = false;
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
tick = !tick;
label1.Text = "Key Pressed: " + e.KeyChar;
//animate(sender, e);
if(tick)
timer1.Start();
else
timer1.Stop();
}
First of all i recommend you to use keyDown and keyUp events instead of key press. To solve your problem: simple set a bool = true on keyDown and and the bool = false on keyUp. Now you can check the bool within you tick method and do whatever you want if you detect key is being pressed.

c# Shutdown a system after holding yes for 5 seconds

I was wondering if anyone knows how to use a dialog box to create a hold down button event. Here is the scenerio:
a user would like to shutdown their system, but because it is critical that they confirm, that user must hold the button for 5 seconds before the action can be done.
I am trying to do it in a yes no scenario ie.
To confirm shutdown please hold "Yes" for 5 seconds.
Anyone done this before able to offer a little help/insight?
Try using a button's Mouse_Down & Mouse_Up event, and a timer (this assumes you're using WinForms).
private void button1_MouseDown(object sender, MouseEventArgs e)
{
if (this.timer1.Enabled == false)
{
this.timer1.Interval = 5000;
this.timer1.Enabled = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
this.timer1.Enabled = false;
MessageBox.Show("Shutdown!");
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
timer1.Enabled = false;
}
You could capture the button press on 'mousedown', and start a 5-second timer. Once the timer completes, shutdown is initiated. If a 'mouseup' event happens, it could stop and reset the timer.
Sure, handle BOTH the mousedown event and the mouseup event. Start a timer on the mousedown and see how long it has run on the mouseup. Done!
You could do this any number of ways. The first that comes to my mind would be to spin off a thread that waits 5 seconds and is simply aborted if the user's mouse comes back up.
Thread shutdown;
private void button1_MouseDown(object sender, MouseEventArgs e)
{
shutdown = new Thread(()=>ShutDown());
shutdown.Start();
}
private void ShutDown()
{
Thread.Sleep(5000);
Console.Write("5 seconds has elapsed");
// Do something.
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
if (shutdown != null)
{
shutdown.Abort();
shutdown = null;
}
}
Low overhead and you're not adding additional supporting controls for something this simple.
Why bother when you can just use getAsyncKeyState()? Tell them to hold down 'y' for 5 seconds. You can find a reference here: http://www.pinvoke.net/default.aspx/user32.getasynckeystate
Or you can do it your way and start a timer on MouseDown, then on MouseUp, end the timer and then see if it's more or less than 5 seconds. http://msdn.microsoft.com/en-us/library/system.windows.forms.control.mousedown%28VS.71%29.aspx
You can use the Form.MouseDown events do detect that the user has pressed the mouse button. In the event handler, check to see if cursor is over the button or not (the event is passed in the coordinates of the cursor). You can then enable a timer which will tick in 5 seconds, and perform the shutdown when the timer ticks.
When the user first clicks YES, start a timer that repeatedly checks if the mouse location is inside of the button. After 5 seconds has elapsed, proceed with the shutdown. If the user moves the mouse out of the button, stop the timer.
private DateTime mouseDownTime;
private void Button_MouseDown(object sender, MouseButtonEventArgs e)
{
mouseDownTime = DateTime.Now;
}
private void Button_MouseUp(object sender, MouseButtonEventArgs e)
{
if (mouseDownTime.AddSeconds(5) < DateTime.Now)
MessageBox.Show("You held it for 5 seconds!");
}
You can set up a timer on the MouseDown event, and if the mouse capture changes (check the MouseCaptureChanged event) to false before the timer event fires, cancel the timer.

PopUp window on a specific time in WPF?

How can I create and show a popup window at a specific time in WPF?
What I mean how to display the window on the side of system tray.
You could use a timer if you're trying to make the thing popup in a certain number of hours/seconds/minutes (or work out how many hours/seconds/minutes are left until your specific time comes around).
private System.Windows.Threading.DispatcherTimer popupTimer;
// Whatever is going to start the timer - I've used a click event
private void OnClick(object sender, RoutedEventArgs e)
{
popupTimer = new System.Windows.Threading.DispatcherTimer();
// Work out interval as time you want to popup - current time
popupTimer.Interval = specificTime - DateTime.Now;
popupTimer.IsEnabled = true;
popupTimer.Tick += new EventHandler(popupTimer_Tick);
}
void popupTimer_Tick(object sender, EventArgs e)
{
popupTimer.IsEnabled = false;
// Show popup
// ......
}
Ok, so you also want to know how to do a notifier popup type thing, which maybe this article in CodeProject might help.
Check out this question for firing an event at a set time.
You might want to check out DispatcherTimer.

Categories

Resources