Preface

In software development, sometimes you need to add buttons to the UI page and click the buttons to execute business logic. If it is a regular event, it can be implemented by binding the event. However, in some designs, the event response is executed after the key is pressed, but at the same time, we also want to add a button on the UI to respond to the same event. How should we design it?

Of course, we can respond to the event in the UI and then call the business logic to implement it. The problem with this approach is that the UI and business logic are too coupled.

In fact, we can convert UI events into key events, which can not only take advantage of the powerful input system of Unreal Engine, but also significantly reduce logical coupling and improve the maintainability and scalability of the code.

Honor of Kings
Honor of Kings

Some products may be developed on the PC first, and then all input events are responded to through keyboard input, but the product needs to be adapted to the mobile terminal, which cannot be input through the keyboard, but can only be input through the touch screen. We can simulate key input through the program to realize the business design of the virtual keyboard.

Implementation

We can use the following code to send key events to the engine:

cpp
1
2
3
4
5
6
7
8
9
FKeyEvent KeyEvent(
    EKeys::A, // key
    FModifierKeysState(), // modifier key state (Shift, Ctrl, etc.)
    0, // user index
    false, // whether to repeat the key
    0, // character code (ASCII/Unicode)
    0 // keyboard scan code
);
FSlateApplication::Get().ProcessKeyDownEvent(KeyEvent);

Of course, the following solution can also be implemented:

cpp
1
2
FInputKeyEventArgs Args(GEngine->GameViewport->Viewport, 0, EKeys::A, EInputEvent::IE_Pressed);
GEngine->GameViewport->Viewport->InputKey(Args);

When simulating key input, remember not to execute it in Tick, otherwise it will cause the event to be executed repeatedly. And be sure to pay attention to the key events Pressed and Released appearing in pairs, and do not miss any events.

Summary

By simulating key input through the program, you can significantly reduce logical coupling and improve the maintainability and scalability of the code. This design idea is suitable for the development of medium and large projects, which can effectively reduce maintenance costs and enhance the adaptability and scalability of input logic.

In this way, developers can focus on the implementation of core logic without spending too much energy on the interface processing between UI and input. This separation of events and business logic is an important manifestation of the pursuit of modularity and high availability in modern game development.

Engine version: 5.3.2