Timer för att räkna arbetstid

Post date: Aug 27, 2009 6:25:45 AM

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

using System.Timers;

using System.Reflection;

using System.Threading;

namespace TimeCalc

{

/// <summary>

/// Interaction logic for Window1.xaml

/// </summary>

public partial class Window1 : Window

{

TimeSpan _currentTime;

DateTime _startTime;

System.Timers.Timer _tmr;

List<TimedEvent> _completedTimedEvents;

public Window1()

{

InitializeComponent();

_completedTimedEvents = new List<TimedEvent>();

InitTimer();

StartNewTimer();

}

private void InitTimer()

{

_tmr = new System.Timers.Timer(1000);

_tmr.AutoReset = true;

_tmr.Elapsed += new ElapsedEventHandler(tmr_Elapsed);

}

void tmr_Elapsed(object sender, ElapsedEventArgs e)

{

Tick();

SetTimeTextBlock(CurrentTime);

}

private void Button_Click(object sender, RoutedEventArgs e)

{

StartNewTimer();

SetTimeTextBlock(CurrentTime);

}

private void StartNewTimer()

{

_startTime = DateTime.Now;

_tmr.Start();

}

private void Tick()

{

_currentTime = DateTime.Now - _startTime;

}

private void SetTimeTextBlock(string text)

{

this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, (ThreadStart)delegate

{

TimeTextBlock.Text = text;

});

}

public string CurrentTime {

get

{

return string.Format("{0}:{1}:{2}", _currentTime.Hours, _currentTime.Minutes, _currentTime.Seconds);

}

}

private void Button_Click_1(object sender, RoutedEventArgs e)

{

_tmr.Stop();

TimedEvent timedEvent = new TimedEvent();

timedEvent.TaskName = "Jobbar";

timedEvent.StartTime = _startTime;

timedEvent.EndTime = DateTime.Now;

_completedTimedEvents.Add(timedEvent);

TaskListbox.Items.Add(timedEvent);

SetTimeTextBlock(string.Empty);

}

}

}