前言
当今视觉体验日益重要,Unity不仅仅是一个游戏开发引擎,它也是一个强大的工具,可以用来创建跨平台的桌面应用程序。这篇文章将介绍如何通过C#脚本控制Unity应用窗口的基本属性、自定义窗口的标题栏、应用单开、动态调整窗口尺寸以及实现圆角或直角风格的方法,使应用界面更加流畅和现代化。(工程在文章结尾)
–
一、效果演示
二、实现思路
1、(重点,不做会报错)第一步将Unity的PlayerSetting->Player->OtherSettings->Configuration中的API级别设置为下图所示
1、引用Window32位的API,包括设置隐藏标题栏、设置窗口风格、隐藏窗口、显示窗口、设置圆角窗口等(以下是部分代码,还有开机自启以及托盘相关的都在结尾工程中)
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;
public class WinAPI
{
// 引入用户32.dll库中的ShowWindow函数,用于显示或隐藏窗口
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hwd, int cmdShow);
// 引入用户32.dll库中的GetWindowLong函数,用于获取窗口的特定属性
[DllImport("user32.dll")]
public static extern long GetWindowLong(IntPtr hwd, int nIndex);
// 引入用户32.dll库中的SetWindowLong函数,用于设置窗口的特定属性
[DllImport("user32.dll")]
public static extern void SetWindowLong(IntPtr hwd, int nIndex, long dwNewLong);
// 引入shell32.dll库中的ExtractAssociatedIcon函数,用于从文件路径中提取关联的图标
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr ExtractAssociatedIcon(IntPtr hInst, StringBuilder lpIconPath,
out ushort lpiIcon);
// 添加新的 DllImport,引用Dwmapi.dll库中的DwmSetWindowAttribute函数,用于设置窗口的属性
[DllImport("Dwmapi.dll")]
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
// 引入用户32.dll库中的SetWindowRgn函数,用于设置窗口的区域
[DllImport("user32.dll")]
private static extern int SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool bRedraw);
// 引入gdi32.dll库中的CreateRoundRectRgn函数,用于创建一个圆角矩形区域
[DllImport("gdi32.dll")]
private static extern IntPtr CreateRoundRectRgn(int x1, int y1, int x2, int y2, int cx, int cy);
// 添加 DWM 属性常量
private const int DWMWA_WINDOW_CORNER_PREFERENCE = 33;
// 圆角类型枚举
private enum DWM_WINDOW_CORNER_PREFERENCE
{
DWMWCP_DEFAULT = 0, // 默认设置
DWMWCP_DONOTROUND = 1, // 不使用圆角
DWMWCP_ROUND = 2, // 使用圆角
DWMWCP_ROUNDSMALL = 3 // 使用小圆角
}
/// <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;
#region 应用自启动相关
private const string RegistRun = @"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
private const string RegistWin32ApiExe = "AutoBostAppExe";
/// <summary>
/// 获取可执行文件路径
/// </summary>
private static string GetExePath
{
get
{
var saPath = Application.streamingAssetsPath;
var bufSa = saPath.Split('/');
var end = bufSa[^2] + "/" + bufSa[^1];
var updaterPath = saPath.Replace(end, "AutoBostApp.exe");