0

I am working on pretty much my first program, which is supposed to save when a key press has started and ended into a txt file. The problem is, I can't figure out how to do it all so that the application runs in the background. I have tried with windows forms application, which worked only when it was the focused window. Now I tried it with a console application, but with no luck.

I have searched the web for answers to this problem of mine, but I just can't find one for some reason. I've spent multiple hours trying to solve this problem, and I'm going nowhere.

I managed to get the program to work kind of like a keylogger with GetAsyncKeyState as a console application, but I'd need to know when press started and ended, which I'm not sure if it's possible with it.

So this is the closest I've got to, but this isn't quite what I'm after.

    class Program
    {
        [DllImport("user32.dll")]
        public static extern int GetAsyncKeyState(Int32 i);
        static void Main(string[] args)
        {
            while (true)
            {
                Thread.Sleep(5);

                int keyA = GetAsyncKeyState(65);
                if (keyA == 32769) //if "A" key is pressed
                {
                    Console.WriteLine("A");
                }
            }
        }
    }
Hamunii
  • 1
  • 1
  • Same question already there https://stackoverflow.com/questions/56103251/capturing-keyboard-events-in-c-sharp-windows-service – Rahul Shukla May 10 '21 at 20:32
  • Is something like this that you need? https://github.com/MarvinDrude/Windows-Global-Hotkey or https://www.codeproject.com/Articles/442285/Global-Shortcuts-in-WinForms-and-WPF –  May 10 '21 at 20:54
  • @OlivierRogier I'm not quite sure. If I can use it to give output when first pressed down and when released, then it would do the job. I did look both and couldn't find an answer for my problem. It is as simple as getting 2 outputs from a key press, but still I can't find the answer even from these links, or even from the post that this got linked to as a duplicate. – Hamunii May 11 '21 at 17:50

0 Answers0