L
L
lens23142021-10-30 18:20:44
C++ / C#
lens2314, 2021-10-30 18:20:44

How to output key pressed in label c#?

How to make something like a keylogger that, after pressing button1, will once display the received button in label1 and write it to a variable, I tried to use ReadKey

private void button1_Click(object sender, EventArgs e)
        {
            
            label1.Text = "Нажмите кнопку на которую будет работать макрос";
            label1.Visible = true;
            while (true)
            {
                ConsoleKeyInfo pressed;
                pressed = Console.ReadKey();
                

            }


Visual Studio complains:
System.InvalidOperationException: "Unable to read keys when any application does not have a console or console input was redirected from a file. Try using Console.Read."

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
twobomb, 2021-10-30
@twobomb

That feeling when before that I wrote everything in the console and decided to try gui ....
Judging because it should be a keylogger, you can immediately skip the option of using the keypress event on the form, since reading will only be done with the active form and go to hooks.
First thing that came up on google

V
Vasily Bannikov, 2021-10-30
@vabka

1. Not the studio, but your application itself swears
2. It says in Russian that Console.ReadKey () can only be used in the console
3. So you need to make an event handler for keypresses on the keyboard somewhere, and process them.
Read what a "state machine" is - you will just need to implement it so that when you click on button1, your form goes into the state when the user clicks the button, and after clicking on it, it exits this state and remembers this button.
And there shouldn't be any while(true) in event handlers - it will just hang your application.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question