C# instruction to call a Keydown function?

Hello guys,
What is the C# instruction to call a Keydown function (Key press) with FiveM?
I tried this but doesn’t work:


        public SurvivorsMain()
        {
            Tick += OnTick;
            KeyDown += OnKeyDown;
        }

        private void OnKeyDown(object sender, KeyEventArgs e)
        {

        }

Any help?

Each tick you have to call if(Game.WasControlJustPressed(0, Control.Reload)) for example, will return true when R was pressed,

@Yuval This is what I am currently doing:

            if (Game.IsControlJustReleased(0, Control.Phone))
            {
                //My code here...
            }

But I have to press 3 or 4 times the key before the code is executed. That is why I wanted to execute the code out of the tick function to make it more responsive…

You shouldn’t have to press it multiple times. It should work if you press it once – always. Do you have any await in your OnTick function? If so, that would cause this to not work every press.

There is only one
await Delay(0);
But the Tick calls some async function. Is that the cause of the issue? It should not as they are asynchronous.

You shouldn’t have any delays in the main Tick function. If you need to put any delays, but it inside any of the sub-tasks. Thats probably what is causing it, because it will be skipping a frame.

Is Tick function not an async function? Because visual studio warn me that the function will be synchronous without an await.

It is, but don’t worry about the warning if you remove the delay. It will still work fine.

1 Like

And you are right. Now it is very responsive and works like a charm. Thank you Briglair.

2 Likes

for avoid the warning , just put at the end of your OnTick task : await Task.FromResult(0);

ps : check closer in the Game class you have different function about the key for get a press key , and pressed key ect… very usefull depending what you want to do

Thank you @304bl. It works . I have also checked the different functions for keys. Some are very sensitive, press once and you get your code executed several times :smile:

yes exactly that why sometime you will have to use a bool for be sure the func is execute only once.

1 Like