Key Events
Introduction
Key Events represent the MSFS control binding system: all controls that are bindable though the simulator controls menu are available to also be driven and read via code. Examples of things you can bind in the controls menu would be pressing various autopilot buttons, moving your trim axis, turning on an engine starter, and the like.
All of these events have names within MSFS and we can use the names to interact with those events within Javascript.
Initiating A Key Event
In the Javascript framework, key events are run by using the SimVar class, and prefixing the key event name with a K: (which gives key events their alternate name, K events). For example, to send the simulator the event to increase the flaps position:
//Will do the same thing as if the button bound to 'Flaps Increase' in the
//menu was pressed
SimVar.SetSimVarValue('K:FLAPS_INCR', 'number', 0);
For events that don't take a value, the second two parameters are ignored. But, some key events do take a value (such as a control axis):
SimVar.SetSimVarValue('K:AXIS_ELEVATOR_SET', 'number', -8225);
Listening For A Key Event
For many addons, it can be beneficial to also be notified when a key event has been received by the simulator, and then take appropriate action. This could be augmenting some action the sim is already taking, or even blocking the sim from recieving the event altogether and entirely replacing behavior.
//The key intercept manager requires a EventBus to publish to
const eventBus = new EventBus();
//Get the key intercept manager
const manager = await KeyInterceptManager.getManager(eventBus);
//Set the AP nav hold key event to be intercepted, but still pass through to the sim
manager.interceptKey('AP_NAV1_HOLD', true);
//Set the AP master on/off key event to be intercepted, but _not_ pass through to the sim
manager.interceptKey('AP_MASTER', false);
const subscriber = eventBus.getSubscriber<KeyEvents>();
subscriber.on('key_intercept').handle(keyData => {
switch (keyData.key) {
case 'AP_NAV1_HOLD':
console.log('Toggled autopilot nav hold!');
break;
case 'AP_MASTER':
console.log('Toggled autopilot master!');
break;
}
});
If you have set the key intercept to not pass through to the simulator, the simulator will not respond to the key event in any way: from the inside of the simulator's perspective, the key event was never sent. This is a very powerful tool for crafting custom behavior for many complex systems, but requires some care.
More Information
For more information about the key event IDs that are available and what they do, please see the MSFS SDK Documentation.