使用GetTickCount函数创建身份验证控制台应用程序

时间:2013-03-16 15:34:47

标签: c#

我正在尝试创建一个简单的登录/身份验证控制台应用程序,例如我有一个字符串testpwd作为我的密码,我希望程序计算用户开始输入密码时的时间(以毫秒为单位)输出每次用户在GetTickCount功能的帮助下从键盘开始输入时,每个用户输入密码所需的秒数。

我不知道如何解决这个问题,但我唯一能做的就是下面的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace LoginSystem
{
    class LSystem
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello! This is simple login system!");
            Console.Write("Write your username here: ");
            string strUsername = Console.ReadLine();
            string strTUsername = "testuser";
            if (strUsername == strTUsername)
            {
                Console.Write("Write your password here: ");
                Console.ForegroundColor = ConsoleColor.Black;
                string strPassword = Console.ReadLine();
                string strTPassword = "testpwd";
                if (strPassword == strTPassword)
                {
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.WriteLine("You are logged in!");
                    Console.ReadLine();

                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.WriteLine("Bad password for user: {0}", strUsername);
                    Console.ReadLine();
                }
            }
            else
            {
                Console.WriteLine("Bad username!");
                Console.ReadLine();
            }
        }
    }
}

3 个答案:

答案 0 :(得分:0)

1-你可以使用DateTime.Now然后减去它们以获得时间跨度。

2-调用GetTickCount,但您需要首先声明它:

[DllImport("kernel32.dll")]
static extern uint GetTickCount();

答案 1 :(得分:0)

一个简单的StopWatch?代码的相关部分可以用这种方式编写

...
Console.ForegroundColor = ConsoleColor.Black;
StopWatch sw = new Stopwatch();
sw.Start();
string strPassword = Console.ReadLine();
sw.Stop()
TimeSpan ts = sw.Elapsed;
string strTPassword = "testpwd";
if (strPassword == strTPassword)
{
    Console.ForegroundColor = ConsoleColor.Gray;
    Console.WriteLine("You are logged in after " + ts.Milliseconds.ToString() + " milliseconds");
    Console.ReadLine();
}
.....

答案 2 :(得分:0)

首先,您的问题很难理解。如果我正确地读了你,你希望在用户开始输入时开始计时,并在用户按下回车时停止?如何使用System.Diagnostics.Stopwatch class

在调用Console.ReadLine()之前,启动一个新的Stopwatch(),然后调用Start()方法。

在Console.ReadLine()之后,立即停止秒表:

        Console.Write("Write your username here: ");

        var stopwatch = new System.Diagnostics.Stopwatch();
        stopwatch.Start();

        string strUsername = Console.ReadLine();

        stopwatch.Stop();

        string strTUsername = "testuser";
相关问题