.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MywinClass.generated.h"
UCLASS()
class SPLINECPP_API AMywinClass : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AMywinClass();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
UFUNCTION(BlueprintCallable,Category = "myactor")
static void FindWindowAndTop(FString name,bool SetTop);
UFUNCTION(BlueprintCallable,Category = "myactor")
static void OpenCoustomFile(FString FileName);
UFUNCTION(BlueprintCallable,Category = "myactor")
static bool CloseCoustomFile(FString FileName);
UFUNCTION(BlueprintCallable,Category = "myactor")
static int CMD(FString FileName);
};
.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "MywinClass.h"
#include <Windows.h>
// Sets default values
AMywinClass::AMywinClass()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AMywinClass::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AMywinClass::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void AMywinClass::FindWindowAndTop(FString name,bool SetTop)
{
const TCHAR* WindowName = *name;
HWND hWnd=NULL;
hWnd=FindWindowW(NULL,WindowName);
if(hWnd==NULL)
{
return;
}
else
{
ShowWindow(hWnd,SW_SHOWMAXIMIZED);
ShowWindow(hWnd, SW_RESTORE);
if (SetTop)
{
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
else
{
SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
}
}
void AMywinClass::OpenCoustomFile(FString FileName)
{
FString abc = FPaths::ProjectDir() + FileName;
LPCWSTR MyLpcwstr = nullptr;
MyLpcwstr = TCHAR_TO_WCHAR(*abc);
ShellExecute(NULL,L"open",MyLpcwstr,NULL,NULL,SW_SHOWNORMAL);
}
bool AMywinClass::CloseCoustomFile(FString FileName)
{
const TCHAR* windowname = *FileName;
HWND CoustomHwnd = FindWindow(NULL,windowname);
if (IsWindow(CoustomHwnd) != 0)
{
//同步调用
//SendMessage(CoustomHwnd,WM_CLOSE,0,0);
//异步调用
PostMessage(CoustomHwnd,WM_CLOSE,0,0);
return true;
}
else
{
return false;
}
}
int AMywinClass::CMD(FString FileName)
{
const TCHAR* windowname = *FileName;
int result = system("cmd /c windowname");
if (result == 0) {
// 命令执行成功
// 可以继续处理或执行其他操作
} else {
// 命令执行失败
// 可以根据具体情况处理错误
}
return 0;
}