廢話不多說:
using UnityEngine;
using System;
using System.Runtime.InteropServices;
public class TransparentWindow : MonoBehaviour
{
[DllImport("user32.dll")]
private static extern IntPtr GetActiveWindow();
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, uint dwNewLong);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
private static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
private const int GWL_EXSTYLE = -20;
private const uint WS_EX_LAYERED = 0x00080000;
private const uint WS_EX_TRANSPARENT = 0x00000020;
private const uint LWA_ALPHA = 0x00000002;
private IntPtr hWnd;
private Material transparentMaterial;
private void Start()
{
#if UNITY_STANDALONE_WIN
hWnd = GetActiveWindow();
uint exStyle = (uint)SetWindowLong(hWnd, GWL_EXSTYLE, WS_EX_LAYERED | WS_EX_TRANSPARENT);
if (exStyle == 0)
{
Debug.LogError("Failed to set window style. Error: " + Marshal.GetLastWin32Error());
return;
}
if (!SetLayeredWindowAttributes(hWnd, 0, 255, LWA_ALPHA))
{
Debug.LogError("Failed to set window attributes. Error: " + Marshal.GetLastWin32Error());
return;
}
SetWindowPos(hWnd, IntPtr.Zero, 0, 0, 0, 0, 0x0002 | 0x0001 | 0x0004);
transparentMaterial = new Material(Shader.Find("Unlit/Transparent"));
#else
Debug.LogWarning("TransparentWindow is only supported on Windows standalone builds.");
#endif
}
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
#if UNITY_STANDALONE_WIN
if (transparentMaterial != null)
{
Graphics.Blit(source, destination, transparentMaterial);
}
else
{
Graphics.Blit(source, destination);
}
#else
Graphics.Blit(source, destination);
#endif
}
private void OnDestroy()
{
if (transparentMaterial != null)
{
Destroy(transparentMaterial);
}
}
}
使用步驟: