#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")));
        }