Unity实战篇 | 使Unity打包的exe程序始终保持屏幕最前端【文末送书】

文章目录
📢前言
-
大家在平时使用一些软件APP的时候,会看到有些软件打开后有个选项可以将
该窗口置顶
。 - 置顶之后这个窗口就会显示在屏幕最前方,不会被其他应用窗口遮挡。
- 想要实现这个功能的话在Unity中并没有找到相关的API可以直接拿来使用。
- 所以在查阅一番资料之后,最终选择使用Windows句柄调用相关文档API来实现。
- 下面就来看看怎样操作吧,可以将文中关键脚本挂载到相关场景中就可以使用该功能。
🎬Unity实战篇 |使Unity打包的exe程序始终保持屏幕最前端

一、编写核心脚本代码
实现该功能主要是使用了几个关键的Windows的API,分别是下面几个函数:
其中关键函数的意义和关键参数,可以到指定链接查看详细信息,这里就不多做阐述了。
辅助脚本:C.cs
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
public class C
public delegate bool WNDENUMPROC(IntPtr hwnd, uint lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, uint lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetParent(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref uint lpdwProcessId);
[DllImport("kernel32.dll")]
public static extern void SetLastError(uint dwErrCode);
public static IntPtr GetProcessWnd()
IntPtr ptrWnd = IntPtr.Zero;
uint pid = (uint)Process.GetCurrentProcess().Id; // 当前进程 ID
bool bResult = EnumWindows(new WNDENUMPROC(delegate (IntPtr hwnd, uint lParam)
uint id = 0;
if (GetParent(hwnd) == IntPtr.Zero)
GetWindowThreadProcessId(hwnd, ref id);
if (id == lParam) // 找到进程对应的主窗口句柄
ptrWnd = hwnd; // 把句柄缓存起来
SetLastError(0); // 设置无错误
return false; // 返回 false 以终止枚举窗口
return true;
}), pid);
return (!bResult && Marshal.GetLastWin32Error() == 0) ? ptrWnd : IntPtr.Zero;
}
核心脚本如下:WindowActive.cs
//公众号:呆呆敲代码的小Y
using UnityEngine;
using System.Runtime.InteropServices;
using System;
public class WindowActive : MonoBehaviour
[DllImport("User32.dll")]
extern static bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32.dll")]
extern static bool ShowWindow(IntPtr hWnd, short State);
[DllImport("user32.dll ")]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
const UInt32 SWP_NOSIZE = 0x0001;
const UInt32 SWP_NOMOVE = 0x0002;
IntPtr hWnd;
//public float Wait = 0;//延迟执行
//public float Rate = 1;//更新频率
public bool KeepForeground = true;//保持最前
void Start()
hWnd = C.GetProcessWnd();
Active();
//InvokeRepeating("Active", Wait, Rate);
/// <summary>
/// 激活窗口
/// </summary>
void Active()
if (KeepForeground)
ShowWindow(hWnd, 1);
SetForegroundWindow(hWnd);
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);