unity是没有提供windows标题修改和窗口图标更换的接口,所以要自己实现。
另外没有Icon这个类型,所以直接使用了API来进行对图标的操作。
这个类要挂在一个物体上,Awake进行初始化后才能使用。
先枚举寻找窗口返回句柄,然后通过SetWindowText设置窗口标题,
ExtractIcon来创建图标获取图标句柄,然后使用SendMessage来向窗口发送WM_SETICON (0x80)消息。
using System; using System.Runtime.InteropServices; using UnityEngine; public class ProgramWindow : MonoBehaviour { public static ProgramWindow Instance; #region WIN32API delegate bool EnumWindowsCallBack(IntPtr hwnd, IntPtr lParam); [DllImport("user32", CharSet = CharSet.Unicode)] static extern bool SetWindowTextW(IntPtr hwnd, string title); //回调指针,值 [DllImport("user32")] static extern int EnumWindows(EnumWindowsCallBack lpEnumFunc, IntPtr lParam); [DllImport("user32")] static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref IntPtr lpdwProcessId); [DllImport("user32")] static extern bool CloseWindow(IntPtr hwnd); [DllImport("user32")] static extern int SendMessageA(IntPtr hWnd, int wMsg, int wParam, IntPtr lParam); [DllImport("shell32")] static extern IntPtr ExtractIcon(int hInst, string lpszExeFileName, int nIconIndex); #endregion /// <summary> /// 当前窗口句柄 /// </summary> public static IntPtr myWindowHandle; public void Start() { #if UNITY_STANDALONE_WIN IntPtr handle = (IntPtr)System.Diagnostics.Process.GetCurrentProcess().Id; //获取进程ID EnumWindows(new EnumWindowsCallBack(EnumWindCallback), handle); //枚举查找本窗口 #endif } /// <summary> /// 改变窗口标题 /// </summary> /// <param name="title"></param> public static void ChangeTitle(string title) { #if UNITY_STANDALONE_WIN SetWindowTextW(myWindowHandle, title);//设置窗口标题 #endif } /// <summary> /// 更改窗口图标 /// </summary> /// <param name="icon">图标路径</param> public static void ChangeICON(string icon) { #if UNITY_STANDALONE_WIN IntPtr result = ExtractIcon(0, icon, 0); if (result != IntPtr.Zero) SendMessageA(myWindowHandle, 0x80, 0, result); else Debug.Log ("SetIconFail" ); #endif } private bool EnumWindCallback(IntPtr hwnd, IntPtr lParam) { #if UNITY_STANDALONE_WIN IntPtr pid = IntPtr.Zero; GetWindowThreadProcessId(hwnd, ref pid); if (pid == lParam) //判断当前窗口是否属于本进程 { myWindowHandle = hwnd; return false; } return true; #endif return false; } private void Awake() { Instance = this; } }
文章评论