#625 – Converting a Keypress Timestamp to a DateTime

The various keypress (up/down) event handlers will all have access to a KeyEventArgs object, which includes a Timestamp property.  This property indicates the exact time that the key was pressed or released.

The value of the Timestamp property is an int, rather than a DateTime object.  The integer represents the number of milliseconds since the last reboot.  When the value grows too large to store in the integer object, it resets to 0.  This happens every 24.9 days.

You can convert this timestamp value to an actual date/time by starting with the current time and subtracting the number of milliseconds that have elapsed since the timestamp.  You can read the current number of milliseconds since reboot from the Environment.TickCount property.

        private void TextBox_KeyDown(object sender, KeyEventArgs e)
            DateTime dt = DateTime.Now;
            dt.AddMilliseconds(e.Timestamp - Environment.TickCount);

            Trace.WriteLine(string.Format("Key DOWN at: {0}", dt.ToString("h:mm:ss.FFF tt")));

#370 – Binding a Label’s Content to the Current Date and Time, part II

You can bind a Label control’s Content property to the DateTime.Now property to display the current date or time, but the label will not update when the time changes.

To get a Label control that continuously updates with the current time, you can bind to a property that updates periodically and notifies us using the INotifyPropertyChanged interface.  We can do this by creating a timer that updates a DateTime property whenever it ticks.

Here’s the XAML:

        <Label Content="{Binding CurrentDateAndTime}" ContentStringFormat="Current time - {0:T}"/>

In the code-behind, we define the property and set up a timer.

        public DateTime CurrentDateAndTime { get; set; }

        public MainWindow()
            this.DataContext = this;

            DispatcherTimer dayTimer = new DispatcherTimer();
            dayTimer.Interval = TimeSpan.FromMilliseconds(500);
            dayTimer.Tick += new EventHandler(dayTimer_Tick);

Whenever the timer fires, we update our property and fire the INotifyPropertyChanged.PropertyChanged event.

        void dayTimer_Tick(object sender, EventArgs e)
            CurrentDateAndTime = DateTime.Now;

            PropertyChanged(this, new PropertyChangedEventArgs("CurrentDateAndTime"));

The end result: