一、前言
游戏项目是使用Unity
开发的,发布了PC
平台的exe
。
然后策划提出这么一个需求:
可否让玩家点击窗口的关闭按钮的时候不关闭程序,而是执行最小化。
说实话,这样做不是很厚道,不过,技术上是可以实现的。
本文实现的效果如下:
二、创建脚本
创建一个WindowsStyle
脚本,挂到场景的某个物体上,比如我挂到Main Camera
上。
三、代码
using System;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;
public class WindowsStyle : MonoBehaviour
{
public Button hideBarBtn;
public Button showBarBtn;
public Button hideCloseBtn;
public Button showCloseBtn;
private void Awake()
{
// 获得窗口句柄
var hwd = GetForegroundWindow();
// 隐藏标题栏
hideBarBtn.onClick.AddListener(() =>
{
var wl = GetWindowLong(hwd, GWL_STYLE);
wl &= ~WS_CAPTION;
SetWindowLong(hwd, GWL_STYLE, wl);
});
// 显示标题栏
showBarBtn.onClick.AddListener(() =>
{
var wl = GetWindowLong(hwd, GWL_STYLE);
wl |= WS_CAPTION;
SetWindowLong(hwd, GWL_STYLE, wl);
});
// 隐藏关闭按钮
hideCloseBtn.onClick.AddListener(() =>
{
var wl = GetWindowLong(hwd, GWL_STYLE);
wl &= ~WS_SYSMENU;
SetWindowLong(hwd, GWL_STYLE, wl);
});
// 显示关闭按钮
showCloseBtn.onClick.AddListener(() =>
{
var wl = GetWindowLong(hwd, GWL_STYLE);
wl |= WS_SYSMENU;
SetWindowLong(hwd, GWL_STYLE, wl);
});
}
/// <summary>
/// 点击窗口的x按钮,会执行这个函数
/// </summary>
private void OnApplicationQuit()
{
Application.wantsToQuit += () =>
{
// 获得窗口句柄
var hwd = GetForegroundWindow();
// 设置窗口最小化
ShowWindow(hwd, SW_SHOWMINIMIZED);
// 阻止程序被关闭
return false;
};
}
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hwd, int cmdShow);
[DllImport("user32.dll")]
public static extern long GetWindowLong(IntPtr hwd, int nIndex);
[DllImport("user32.dll")]
public static extern void SetWindowLong(IntPtr hwd, int nIndex, long dwNewLong);
/// <summary>
/// 最小化
/// </summary>
const int SW_SHOWMINIMIZED = 2;
/// <summary>
/// 最大化
/// </summary>
const int SW_SHOWMAXIMIZED = 3;
/// <summary>
/// 还原
/// </summary>
const int SW_SHOWRESTORE = 1;
/// <summary>
/// 窗口风格
/// </summary>
const int GWL_STYLE = -16;
/// <summary>
/// 标题栏
/// </summary>
const int WS_CAPTION = 0x00c00000;
/// <summary>
/// 标题栏按钮
/// </summary>
const int WS_SYSMENU = 0x00080000;
}
四、赋值脚本的按钮成员
使用UGUI
创建四个按钮,赋值给脚本的按钮成员对象。
五、打包运行测试
发布PC
平台的exe
。
发布成功后,运行测试效果如下: