Unity教程之-Unity3d发布exe启动窗口最大化

 

上篇文章,《Unity教程之-Unity3d去掉exe版本的边框》本篇文章我们来学习下另一个开发技巧,Unity3d发布exe启动窗口最大化,废话不多说,贴上代码


using System.Runtime.InteropServices;
using UnityEngine;

/**
* 窗口最大化脚本
*/

public class WindowMAX : MonoBehaviour
{
[DllImport("user32.dll", EntryPoint = "FindWindow")]
private static extern System.IntPtr FindWindow(System.String className, System.String windowName);

[DllImport("user32.dll")]
private static extern int GetForegroundWindow();

[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(int hWnd, int nCmdShow);

[DllImport("user32.dll")]
static extern bool SetWindowPos(int hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

const int HWND_TOPMOST = -1;
const int HWND_NOTOPMOST = -2;
const uint SWP_NOSIZE = 0x0001;
const uint SWP_NOMOVE = 0x0002;
const uint SWP_SHOWWINDOW = 0x0040;
private bool wasFullScreen = false;
private Resolution resFullScreen;
private int hwnd;

private void Awake()
{
resFullScreen = Screen.currentResolution;
hwnd = GetMainWindow();
}

void OnApplicationFocus(bool focusStatus)
{
if (focusStatus && Application.platform != RuntimePlatform.WindowsEditor)
{
if (hwnd != 0)
{
SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
}
}
}

void Update()
{
if (Screen.fullScreen)
{
if (!wasFullScreen)
{
Screen.SetResolution(resFullScreen.width, resFullScreen.height, true);
wasFullScreen = true;
}
}
else if (wasFullScreen)
{
if (hwnd != 0)
{
ShowWindowAsync(hwnd, 3); // SW_SHOWMAXIMIZED
}
wasFullScreen = false;
}
}
private int GetMainWindow()
{
System.IntPtr hwnd = FindWindow("UnityWndClass", null);
if (hwnd.ToInt32() != 0)
return hwnd.ToInt32();
return GetForegroundWindow();
}

}

好了本篇unity3d教程到此结束,下篇我们再会!