【Unity】透明窗口脚本

using System;
using UnityEngine;
using System.Runtime.InteropServices;

namespace BBKL
{
    public class 窗体穿透 : MonoBehaviour
    {

        // 定义Margins结构体,用于设置窗口边距
        private struct Margins
        {
            public int cxLeftWidth;       // 左边距
            public int cxRightWidth;      // 右边距
            public int cyTopHeight;       // 上边距
            public int cyBottomHeight;    // 下边距
        }

        // 导入user32.dll中的GetActiveWindow函数,用于获取活动窗口句柄
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        private static extern IntPtr GetActiveWindow();

        // 导入Dwmapi.dll中的DwmExtendFrameIntoClientArea函数,用于将窗口边框扩展到客户区
        [DllImport("Dwmapi.dll", CharSet = CharSet.Unicode)]
        private static extern uint DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Margins margins);

        // 导入user32.dll中的SetWindowLong函数,用于更改窗口的扩展样式
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        private static extern int SetWindowLong(IntPtr hWnd, int nIndex, uint dwNewLong);

        // 导入user32.dll中的SetWindowPos函数,用于设置窗口的位置和大小
        [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);

        // 导入user32.dll中的SetLayeredWindowAttributes函数,用于设置分层窗口的透明度和颜色键
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        private static extern int SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);

        // 常量定义
        private const int GWL_EXSTYLE = -20;          // 扩展样式索引
        private const uint WS_EX_LAYERED = 0x00080000; // 分层窗口样式

        // 设置窗口置顶
        private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        private const uint LWA_COLORKEY = 0x00000001; // 使用颜色键

        // 窗口句柄
        private IntPtr hWnd;

        private void Start()
        {
#if !UNITY_EDITOR_
            // 获取活动窗口句柄
            hWnd = GetActiveWindow();

            // 设置窗口边距,-1表示将边框扩展到整个窗口
            var margins = new Margins { cxLeftWidth = -1 };
            DwmExtendFrameIntoClientArea(hWnd, ref margins);

            // 设置窗口为分层窗口
            SetWindowLong(hWnd, GWL_EXSTYLE, WS_EX_LAYERED);

            // 设置窗口的透明度属性,这里设置为颜色键模式
            //第二个值就是要替换的颜色,对应颜色将置为透明
            SetLayeredWindowAttributes(hWnd, 0, 0, LWA_COLORKEY);

            // 将窗口设置为置顶
            SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, 0);
#endif

            // 设置主摄像机的背景颜色为完全透明
            Camera.main.backgroundColor = new Color(0, 0, 0, 0);
        }
    }
}
posted @ 2025-02-28 17:46  YanSss  阅读(130)  评论(0)    收藏  举报