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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: