1

I am making program that every pressed key will be saved into text file. My goal is to save every keystroke in new line so for example if you press "x" and then "y" I want this "x" be saved in first line and "y" in second.

           while (true)
        {
            Thread.Sleep(10);
            for (int i = 0; i < 255; i++)
            {
                int keyState = GetAsyncKeyState(i);
                if (keyState == 1 || keyState == -32767)
                {
                    Console.WriteLine((Keys)i);
                    string key = Convert.ToString((Keys)i);
                    //StreamWriter writer = new StreamWriter(pathTxt); <-- this is what I have tried but it's all the time replacing keystroke in first line
                    //writer.WriteLine(key + Enviroment.NewLine);
                    //writer.Close();
                    break;
                }
            }
        }

What I have tried:

My goal is to save every keystroke in new line.

Anonymous-User
  • 43
  • 1
  • 2
  • 7
  • You may be interested in a 'key hook' instead of looping constantly to check the key states. Take a look at: https://stackoverflow.com/questions/15597890/global-keyhook-in-c-sharp – Wiz Apr 03 '20 at 14:13

1 Answers1

2

You can use the code as below. we have to have the streamwriter open and then inside the loop, you can write, once done, you can flush the stream and close for persistence to the disk (file)

Approach-1

using(StreamWriter writer = new StreamWriter(pathTxt)) {
    while (true)
    {
        Thread.Sleep(10);
        for (int i = 0; i < 255; i++)
        {
            int keyState = GetAsyncKeyState(i);
            if (keyState == 1 || keyState == -32767)
            {
                Console.WriteLine((Keys)i);
                string key = Convert.ToString((Keys)i);
                writer.WriteLine(key + Enviroment.NewLine);

                break;
            }
        }
    }
    writer.Flush();
    writer.Close();
}

Approach2-Efficient one The best approach would be to use a StringBuilder and append each keystroke to it and finally write to the file.

StringBuilder keyStrokes = new StringBuilder();
while (true)
{
    Thread.Sleep(10);
    for (int i = 0; i < 255; i++)
    {
        int keyState = GetAsyncKeyState(i);
        if (keyState == 1 || keyState == -32767)
        {
            Console.WriteLine((Keys)i);
            string key = Convert.ToString((Keys)i);
            keyStrokes.appendLine(key);
            break;
        }
    }
}

using(StreamWriter writer = new StreamWriter(pathTxt)) {
    writer.WriteLine(keyStrokes);
    writer.Flush();
    writer.Close();
}
Saravanan
  • 7,637
  • 5
  • 41
  • 72