In Unreal Engine, you can determine the currently focused widget in both Slate and UMG UI systems.
Slate
To get the currently focused Slate widget, you can use the following code snippet:
// Instead of 0, you can pass the user index if you have multiple users
TSharedPtr<SWidget> FocusedSlateWidget = FSlateApplication::Get().GetUserFocusedWidget(0);
UMG
Getting the currently focused UMG widget is a bit more involved, since there is no direct function to get it or the place where it is stored. However, you can iterate over all UMG widgets and compare their cached Slate widgets to the focused one. This approach is not recommended for performance-critical code, but it can be useful for debugging or testing purposes. Here is an example function that does this:
UFUNCTION(BlueprintCallable)
static UWidget* GetFocusedUMGWidget()
{
TSharedPtr<SWidget> FocusedSlateWidget = FSlateApplication::Get().GetUserFocusedWidget(0);
if (!FocusedSlateWidget.IsValid())
{
UE_LOG(LogTemp, Warning, TEXT("No focused Slate widget found"));
return nullptr;
}
for (TObjectIterator<UWidget> Itr; Itr; ++Itr)
{
UWidget* CandidateUMGWidget = *Itr;
if (CandidateUMGWidget->GetCachedWidget() == FocusedSlateWidget)
{
UE_LOG(LogTemp, Warning, TEXT("Focused UMG widget found: %s"), *CandidateUMGWidget->GetName());
return CandidateUMGWidget;
}
}
UE_LOG(LogTemp, Warning, TEXT("No focused UMG widget found"));
return nullptr;
}