# bindKey (Shared)

> Binds a key to a function or a command. The function runs when the key is pressed, released or both.

- **Platform**: MY Multiplayer (MYMP)
- **Kind**: Lua Function
- **Side**: Shared
- **Category**: Keyboard
- **URL**: https://wiki.mymp.gg/en/bindKey

## Syntax

```lua
bool bindKey(player thePlayer, string key, string keyState, function|string handler, any ...)
```

## Parameters

| Name | Type | Description |
| --- | --- | --- |
| `thePlayer` | `player` | Server only: the player the bind belongs to. On the client, leave this argument out. |
| `key` | `string` | The key's name, in any case: `a` to `z`, `0` to `9`, `F1` to `F12`, `mouse1` to `mouse5`, `mouse_wheel_up`, `mouse_wheel_down`, `arrow_l`, `num_0`, `space`, `enter`, `lshift` and others. |
| `keyState` | `string` | When to fire: `"down"` on press, `"up"` on release or `"both"` on either. |
| `handler` | `function\|string` | The function to call or the name of the command to run. |
| `...` | `any` | With a function, extra arguments passed to it. With a command, one string holding the command's arguments. |

## Returns

`true` if the bind was made. `false` if it already existed or the command is empty.

The function receives `(key, state, ...)`, with the player first on the server, and the state is `"down"` or `"up"`. A command bound on the client runs as if typed in the console; on the server, it runs the `addCommandHandler` handlers with the player. A server bind only fires when the client reports the key, which it does not if `onClientKey` was cancelled. A resource's binds go away when it stops, and a player's when they leave.

## Example

```lua
local function toggleEngine(player, key, state)
    local vehicle = getPedOccupiedVehicle(player)
    if vehicle then
        setVehicleEngineState(vehicle, not getVehicleEngineState(vehicle))
    end
end

addEventHandler("onPlayerJoin", root, function()
    bindKey(source, "k", "down", toggleEngine)
end)
```

## See also

- [unbindKey (Shared)](https://wiki.mymp.gg/en/unbindKey.md): Removes binds this resource made on a key.
- [isKeyBound (Shared)](https://wiki.mymp.gg/en/isKeyBound.md): Tells whether this resource bound a function to a key.
- [addCommandHandler (Shared)](https://wiki.mymp.gg/en/addCommandHandler.md): Registers a function that runs when the command is typed in the console. The arguments arrive as space-separated strings.
- [onClientKey (Client)](https://wiki.mymp.gg/en/onClientKey.md): Fired when a key or mouse button is pressed or released. Cancelling the event stops that key's binds and, on a press, hides the key from the game while it is held.
