Jacob Collstrup
Jacob Collstrup

Reputation: 53

Is there a way to get a timestamp of a keystroke in C#?

I'm trying to make a simple stopwatch for a C# class I'm taking. I've googled around all afternoon and found a lot of info that I either don't understand or doesn't quite deal with the problem I'm having.

As I'm currently learning about classes, methods, fields and properties, I'm trying to design my stopwatch like this: Stopwatch concept design

I don't think it needs to be super precise. I'm trying to get a DateTime.now object at the moment a key is pressed on the keyboard:

DateTime.now start = Console.ReadKey();

I've also tried:

var start = DateTime.now(Console.ReadKey());

That doesn't work either.

I've looked at the documentation for the StopWatch class in C#, but that seems way too advanced for me. I've read the page like 3 times and still don't have clue what it does: MS StopWatch class doc

I hope someone here can help me out a bit. best regards, Jacob Collstrup

Upvotes: 0

Views: 282

Answers (3)

Tom Dee
Tom Dee

Reputation: 2674

For a console app you can get the current date and time by doing DateTime.Now. ReadKey blocks the flow so you can call DateTime.Now it directly after the keypress. Do this twice to get a start and end then you can subtract them to get the duration like this:

Console.ReadKey();
DateTime start = DateTime.Now;
Console.ReadKey();
DateTime end = DateTime.Now;
var duration = end.Subtract(start);

DateTime.Subtract will return a TimeSpan so you can either print that out or return it upwards if it is going to be in another function.

Looking at your diagram it is suggesting to use DateTime.Now.Ticks, there doesn't seem to be much advantage to this, as this will be a long and can't use DateTime.Subtract on this (obviously you could just still do end - start). If needed to return the duration in ticks I would recommend doing the same as I said above however when I use the duration variable I would do duration.Ticks.

If you do store the start and end as ticks (long) instead then you convert it into a TimeSpan then you'll need to do this:

TimeSpan ts = new TimeSpan(end - start);  

Upvotes: 3

mm8
mm8

Reputation: 169390

You could get the value of DateTime.Now right after the call to ReadKey():

Console.ReadKey();
DateTime now = DateTime.Now;
Console.WriteLine("Key was pressed at " + now.ToString());

This should work just fine because ReadKey() blocks and returns when the user presses a key.

Upvotes: 2

LordWilmore
LordWilmore

Reputation: 2912

What you want is something like this:

Console.ReadKey();
DateTime start = DateTime.Now;

The call to Console.ReadKey() will block until a key has been pressed. Once that line has returned then you get the current time.

Same for the stop time.

Upvotes: 2

Related Questions