combination of MouseDown and timer - c#

I try to load a function like "holdFunction", during touching(MouseDown) and during at max 1 second .
So when user try to touch and hold for a second I have to call the function, and this isn't related to mouseUp.
Maybe I must to combine these:
private DateTime dtHold;
private void EditProduct_MouseDown(object sender, MouseButtonEventArgs e)
{
dtHold = DateTime.Now;
}
private void EditProduct_MouseUp(object sender, MouseButtonEventArgs e)
{
TimeSpan interval = TimeSpan.FromSeconds(1);
if (DateTime.Now.Subtract(dtHold) > interval)
{
//HoldFunction();
}
}
and
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
private void EditProduct_MouseDown(object sender, MouseButtonEventArgs e)
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 0,1,0);
dispatcherTimer.Start();
}
private int _sec = 0;
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
_sec = _sec + 1;
if (_sec == 2)
{
dispatcherTimer.Stop();
{
//HoldFunction();
}
_sec = 0;
return;
}
}

Is this what you are looking for?
If the User holds the MouseDown for 1 second, the evnt is fired?
public partial class Window2 : Window
{
private DispatcherTimer _DispatcherTimer = new DispatcherTimer();
public Window2()
{
InitializeComponent();
MouseDown += _MouseDown;
MouseUp += _MouseUp;
_DispatcherTimer.Interval = TimeSpan.FromSeconds(1.0);
_DispatcherTimer.Tick += _DispatcherTimer_Tick;
}
private void _DispatcherTimer_Tick(object sender, EventArgs e)
{
_DispatcherTimer.Stop();
Title = DateTime.Now.ToString();
}
private void _MouseUp(object sender, MouseButtonEventArgs e)
{
_DispatcherTimer.Stop();
}
private void _MouseDown(object sender, MouseButtonEventArgs e)
{
_DispatcherTimer.Start();
}
}

Related

A new message box appears with each second after it appears

I ran into an issue where i tried displaying a display box after a countdown reached a certain time but for some odd reason it replicates with each second despite it having already passed the initial time it was supposed to appear. This is what i tried to do but now the timer has stopped and the time remaining column has stopped runng.
public partial class Form1 : Form
{
private List<CSession> sessionlist = new List<CSession>();
private TimeSpan workingTimeSpan = new TimeSpan();
private TimeSpan fiveMinutes = new TimeSpan(0,1,0);
private TimeSpan oneSecond = new TimeSpan(0,0,1);
public Form1()
{
InitializeComponent();
timer1.Enabled = true;
timer1.Start();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void AddTime_Click(object sender, EventArgs e)
{
workingTimeSpan += fiveMinutes;
DisplayWorkingTimeSpan();
}
private void DisplayWorkingTimeSpan()
{
TimerLabel.Text = workingTimeSpan.ToString();
}
private void DecreaseTime_Click(object sender, EventArgs e)
{
TimeSpan fiveMinutes = new TimeSpan(0,5,0);
workingTimeSpan -= fiveMinutes;
DisplayWorkingTimeSpan();
}
private void Confirm_Click(object sender, EventArgs e)
{
CSession newSession = new CSession();
if(PasswordText.Text == "")
{
MessageBox.Show("Password not entered");
return;
}
newSession.password = PasswordText.Text;
newSession.purchased_time = workingTimeSpan;
newSession.remaining_time = workingTimeSpan;
newSession.status = "Online";
sessionlist.Add(newSession);
PasswordText.Text = "";
TimerLabel.Text = "";
workingTimeSpan = new TimeSpan();
}
private void DisplayAllSessions()
{
listView1.Items.Clear();
foreach(CSession c in sessionlist)
{
string[] row = { c.password, c.purchased_time.ToString(), c.remaining_time.ToString(), c.status };
ListViewItem i = new ListViewItem(row);
listView1.Items.Add(i);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
foreach(CSession c in sessionlist)
{
if (c.remaining_time.TotalMinutes == 5)
{
timer1.Stop();
MessageBox.Show("Time almost up for client.");
}
if (c.remaining_time.TotalSeconds < 1)
{
c.status = "Offline";
}
if(c.status == "Online")
{
c.remaining_time -= oneSecond;
}
}
DisplayAllSessions();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
}
Add a flag that gets toggled when you display the message, so you won't display it again:
private bool MessageDisplayed = false;
private void timer1_Tick(object sender, EventArgs e)
{
foreach(CSession c in sessionlist)
{
if (c.remaining_time.TotalMinutes == 5 && !MessageDisplayed) // <-- check the flag
{
MessageDisplayed = true;
MessageBox.Show("Time almost up for client.");
}
if (c.remaining_time.TotalSeconds < 1)
{
c.status = "Offline";
}
if(c.status == "Online")
{
c.remaining_time -= oneSecond;
}
}
DisplayAllSessions();
}
Now you can leave the timer running and your message will only appear once.

How to make a label change its text every some time in C# windows forms

I have a label that I want to update every 5 seconds. It should change from 1921 to 1922 onward till 1992. I have tried using a timer but it gave me an error about being accessed on the wrong thread. The code I used was:
public partial class Form1 : Form
{
int x = 1921;
public Form1()
{
InitializeComponent();
}
System.Timers.Timer myTimer = new System.Timers.Timer(1000);
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
label1.Text = x.ToString();
x += 1;
}
private void Form1_Load(object sender, EventArgs e)
{
myTimer.Elapsed += UpdateLabel;
myTimer.Start();
}
}
Try this:
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
//Invoke makes the UI thread call the delegate.
Invoke((MethodInvoker)delegate {label1.Text = x.ToString(); });
x += 1;
}
try this
private readonly object y = new object();
int x = 1921;
public Form1()
{
InitializeComponent();
}
System.Timers.Timer myTimer = new System.Timers.Timer(1000);
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
Invoke((MethodInvoker)(() => { lock (y) { label1.Text = x.ToString(); x++; } }));
}
private void Form1_Load(object sender, EventArgs e)
{
myTimer.Elapsed += UpdateLabel;
myTimer.Start();
}

Not returning elapsed time in milliseconds

I've built this simple stopwatch program to measure time in the format of: 00:00:000 [minutes:seconds:milliseconds], but the code ignores the format and counts up like this: 00:00:[seconds here][milliseconds here], so as a result I can only get the elapsed time in 10s of milliseconds and not the individual millisecond.
Here's the display:
The actual time elapsed is 3 seconds and 610 milliseconds.
Code:
namespace stopwatch_1
{
public partial class Form1 : Form
{
int timeMinutes, timeSeconds, timeMSeconds;
bool timerActive;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
resetTime();
}
private void buttonStart_Click(object sender, EventArgs e)
{
timerActive = true;
}
private void buttonStop_Click(object sender, EventArgs e)
{
timerActive = false;
}
private void buttonReset_Click(object sender, EventArgs e)
{
resetTime();
}
private void resetTime()
{
timerActive = false;
timeMinutes = 0;
timeSeconds = 0;
timeMSeconds = 0;
}
private void timerStopwatch_Tick(object sender, EventArgs e)
{
if (timerActive == true)
{
timeMSeconds++;
if (timeMSeconds >= 1000)
{
timeMSeconds = 0;
timeSeconds++;
if (timeSeconds >= 60)
{
timeSeconds = 0;
timeMinutes++;
}
}
}
timerDraw();
}
private void timerDraw()
{
labelMinutes.Text = String.Format("{0:00}", timeMinutes);
labelSeconds.Text = String.Format("{0:00}", timeSeconds);
labelMSeconds.Text = String.Format("{0:000}", timeMSeconds);
}
}
}`
The timer interval is set to one, and I've double checked that all variables are pointing to the right labels so I think the problem lies with where I've formatted the string to display, but I'm not sure where I've gone wrong:
private void timerDraw()
{
labelMinutes.Text = String.Format("{0:00}", timeMinutes);
labelSeconds.Text = String.Format("{0:00}", timeSeconds);
labelMSeconds.Text = String.Format("{0:000}", timeMSeconds);
}
I don't really know how to use string.format in this context, so this is probably where I've gone wrong, all help would be appreciated
The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds.
You should use a Stopwatch to get a more accurate resolution:
Stopwatch stopwatch;
public Form1()
{
InitializeComponent();
stopwatch = new Stopwatch();
}
private void Form1_Load(object sender, EventArgs e)
{
// do nothing
}
private void buttonStart_Click(object sender, EventArgs e)
{
stopwatch.Start();
}
private void buttonStop_Click(object sender, EventArgs e)
{
stopwatch.Stop();
}
private void buttonReset_Click(object sender, EventArgs e)
{
stopwatch.Reset();
}
private void timerStopwatch_Tick(object sender, EventArgs e)
{
timerDraw();
}
private void timerDraw()
{
labelMinutes.Text = String.Format("{0:00}", stopwatch.Elapsed.Minutes);
labelSeconds.Text = String.Format("{0:00}", stopwatch.Elapsed.Seconds);
labelMSeconds.Text = String.Format("{0:000}", stopwatch.Elapsed.Milliseconds);
}
EDIT:
You should also reduce the Interval on your timer, since there is no need to refresh the labels on a 1ms interval anymore.

Windows Phone - Increment a value

How can I increment a value per second, when I passed it from another page?
Here is some code , where I get the value from the previous page + I added the Timer.
The Problem is that the EventHandler that has to been created for the Tick, can t be set to OnNavigatedTo.
public partial class Page1 : PhoneApplicationPage
{
DispatcherTimer timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(.1) };
public Page1()
{
InitializeComponent();
this.timer.Tick += new EventHandler(OnNavigatedTo);
this.Loaded += new RoutedEventHandler(OnNavigatedTo);
}
private void ButtonToPage1(object sender, RoutedEventArgs e)
{
App app = Application.Current as App;
MessageBox.Show(app.storeValue);
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string QueryStr = "";
NavigationContext.QueryString.TryGetValue("myNumber", out QueryStr);
int test = (int.Parse(QueryStr));
}
try this:
DispatcherTimer tmr;
int test;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string QueryStr = "";
NavigationContext.QueryString.TryGetValue("myNumber", out QueryStr);
test = (int.Parse(QueryStr));
LoadTimer();
}
public void LoadTimer()
{
tmr = new DispatcherTimer();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
tmr.Interval = new TimeSpan(0, 0, 1);
tmr.Tick += tmr_Tick;
tmr.Start();
});
}
void tmr_Tick(object sender, EventArgs e)
{
test++;
TextBlock.Text = test.ToString();
}
It isn't clear why you can't just follow the tutorial linked in your comment. I guess you misunderstand it and tried to handle Tick event using OnNavigatedTo() method. Yes, that won't work and you aren't supposed to do so.
You're supposed to simply attach event handler method in OnNavigatedTo :
private int myNumber;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string QueryStr = "";
NavigationContext.QueryString.TryGetValue("myNumber", out QueryStr);
myNumber = (int.Parse(QueryStr));
DispatcherTimer newTimer = new DispatcherTimer();
newTimer.Interval = TimeSpan.FromSeconds(1);
//attach event handler method for Tick event
newTimer.Tick += OnTimerTick;
//or attach anonymous method so you don't need OnTimerTick() method :
//newTimer.Tick += (o, e) => { myNumber++; };
newTimer.Start();
}
void OnTimerTick(Object sender, EventArgs args)
{
myNumber++;
}

WPF Audio Player using MediaElement sometimes lags

this is the source code for the audio player:
public partial class MainWindow : Window
{
private DispatcherTimer timer;
public MainWindow()
{
InitializeComponent();
mPlayer.LoadedBehavior = MediaState.Manual;
mPlayer.UnloadedBehavior = MediaState.Manual;
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(500);
timer.Tick += timer_Tick;
mPlayer.MediaOpened += mPlayer_MediaOpened;
}
void mPlayer_MediaOpened(object sender, RoutedEventArgs e)
{
TimeSpan ts = mPlayer.NaturalDuration.TimeSpan;
SeekSlider.Maximum = ts.TotalSeconds;
}
void timer_Tick(object sender, EventArgs e)
{
SeekSlider.Value = mPlayer.Position.TotalSeconds;
}
private MediaElement mPlayer = new MediaElement();
private void ButtonOpen_Click(object sender, RoutedEventArgs e)
{
try
{
var ofd = new OpenFileDialog();
if (ofd.ShowDialog() == true)
{
timer.Start();
mPlayer.Source = new Uri(ofd.FileName);
mPlayer.Volume = VolumeSlider.Value;
timer.Start();
mPlayer.Play();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private void ButtonPlay_Click(object sender, RoutedEventArgs e)
{
mPlayer.Play();
timer.Start();
}
private void ButtonPause_Click(object sender, RoutedEventArgs e)
{
mPlayer.Pause();
timer.Stop();
}
private void ButtonStop_OnClick(object sender, RoutedEventArgs e)
{
timer.Stop();
mPlayer.Stop();
}
private void SeekSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
mPlayer.Position = TimeSpan.FromSeconds(SeekSlider.Value);
}
private void VolumeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
mPlayer.Volume = VolumeSlider.Value;
}
}
I don't know why it has sudden lags. Please help me in finding the problem.
If you think that MediaElement is not appropriate for playing different kinds of audio files. Please suggest an alternative.
The SeekSlider_ValueChanged event was firing too often. so that was causing some lag.
So i solved the problem using the Thumb.DragCompleted event. After this the playback is pretty smooth.

Categories

Resources