How to inject/simulate mouse clicks?

Thanks! this is my first cpp so I used Chatgpt and here is the complete code, I just added some input and output extras:

.cpp

include “MyFunctionLibrary.h”
include “Framework/Application/SlateApplication.h”

void UMyFunctionLibrary::SimulateLeftMouseButtonClick(
bool bButtonDown,
FVector2D& LastCursorPos,
bool& bIsValid,
bool bUseCustomCursorPos,
FVector2D CustomCursorPos
)
{
// Get the Slate application instance
FSlateApplication& SlateApp = FSlateApplication::Get();

// Determine whether to use the custom cursor position or the actual cursor position
if (bUseCustomCursorPos)
{
LastCursorPos = CustomCursorPos;
}
else
{
LastCursorPos = SlateApp.GetLastCursorPos();
}

// Check if the cursor position is valid (not zero)
bIsValid = !LastCursorPos.IsZero();

// Create a pointer event for the left mouse button
FPointerEvent MouseEvent(
0,
SlateApp.CursorPointerIndex,
SlateApp.GetCursorPos(),
LastCursorPos,
SlateApp.GetPressedMouseButtons(),
EKeys::LeftMouseButton,
0,
SlateApp.GetPlatformApplication()->GetModifierKeys()
);

// Simulate the mouse button down or up event
if (bButtonDown)
{
SlateApp.ProcessMouseButtonDownEvent(nullptr, MouseEvent);
}
else
{
SlateApp.ProcessMouseButtonUpEvent(MouseEvent);
}
}

.h

#pragma once

include “Kismet/BlueprintFunctionLibrary.h”
include “MyFunctionLibrary.generated.h”

UCLASS()
class TOPDOWN_API UMyFunctionLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()

public:
UFUNCTION(BlueprintCallable, Category = “Utility”)
static void SimulateLeftMouseButtonClick(
bool bButtonDown,
FVector2D& LastCursorPos,
bool& bIsValid,
bool bUseCustomCursorPos,
FVector2D CustomCursorPos
);
};

1 Like