昨天在群里闲聊,有位群友提了个问题。即如何将游戏窗口置顶,不被其他窗口遮挡。
然后去翻了下代码,发现UE并没有提供相关的函数,只有一个BringToFront函数。
那只好自己写一个了!
分析一下,发现实现原理很简单,我们先获取游戏窗口的句柄,然后用这个句柄调用Windows API把窗口设置为置顶就行了。
直接上代码:
TopWindowBPL.h
#include "Windows/AllowWindowsPlatformTypes.h"
#include "Windows/PreWindowsApi.h"
#include <windows.h>
#include "Windows/PostWindowsApi.h"
#include "Windows/HideWindowsPlatformTypes.h"
#include "TopWindowBPL.generated.h"
/* By ABZ */
UCLASS()
class UTopWindowBPL : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category=Window)
static void SetWindowOnTop(bool StayOnTop = true)
{
if (GEngine && GEngine->GameViewport && GEngine->GameViewport->GetWindow())
{
if (auto NativeWindowPtr = GEngine->GameViewport->GetWindow()->GetNativeWindow())
{
Windows::HWND handle = (Windows::HWND)NativeWindowPtr->GetOSWindowHandle();
::SetWindowPos(handle, StayOnTop ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
}
}
}
};
在蓝图里连线,独立窗口运行测试,工作正常!