前言
在Unity中,如果你想要让打出来的程序窗口始终保持在最前,可以通过调用Windows API实现。在Unity中使用C#调用Windows API函数来使程序窗口置顶。
一、方法一
using System.Runtime.InteropServices;
public class AlwaysOnTop : MonoBehaviour
{
// 声明Windows API函数
[DllImport("user32.dll")]
private static extern int SetWindowPos(int hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);
private const int HWND_TOPMOST = -1;
private const int SWP_NOSIZE = 1;
private const int SWP_NOMOVE = 2;
private const int TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
void Start()
{
// 在启动时将窗口置顶
SetWindowAlwaysOnTop(true);
}
public void SetWindowAlwaysOnTop(bool onTop)
{
// 获取当前窗口句柄
int hWnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
// 调用SetWindowPos函数将窗口置顶或取消置顶
SetWindowPos(hWnd, onTop ? HWND_TOPMOST : 0, 0, 0, 0, 0, TOPMOST_FLAGS);
}
}
二、方法二
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Diagnostics;
using UnityEngine;
public class WindowMod : MonoBehaviour
{
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hPos, int x, int y, int cx, int cy, uint nflags);
[DllImport("User32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("User32.dll", EntryPoint = "SetWindowLong")]
private static ex