【Unity知识分享】Unity实现透明窗口无边框+点透+置顶,可以用于实现桌面宠物和桌面工具

发布于:2025-09-09 ⋅ 阅读:(19) ⋅ 点赞:(0)

1、创建脚本TransparentWindow,实现具体功能逻辑,代码如下

using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;

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")]
    private static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInserAfter, 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 daFlags);

    [DllImport("user32.dll")]
    private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    private const int GWL_EXSTYLE = -20;
    private const int GWL_STYLE = -16;
    private const uint WS_EX_LAYERED = 0x00080000;
    private const uint WS_EX_TOPMOST = 0x00000008;
    private const uint WS_PUPUP = 0x80000000;
    private const uint WS_VISSIBLE = 0x10000000;
    private const uint WS_EX_TOOLWINDOW = 0x00000070; // 可以用来隐藏
    private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
    private const uint SWP_SHOWWINDOW = 0x0040;
    private const uint LWA_COLORKEY = 0x00000001;
    private IntPtr windowHandle;
    private const uint SWP_NOACTIVAIE = 0x0010;

    private IEnumerator Start()
    {
        //yield return new WaitForSeconds(0.5f);
        yield return 0;
        MakeTransparent();
    }

    private void MakeTransparent()
    {
        windowHandle = GetActiveWindow();
        windowHandle = FindWindow("UnityWndClass", null);

        //移除窗口边框
        SetWindowLong(windowHandle, GWL_STYLE, WS_PUPUP | WS_VISSIBLE);

        //设置为分层窗口和置顶
        SetWindowLong(windowHandle, GWL_EXSTYLE, WS_EX_LAYERED | WS_EX_TOPMOST);

        //设置全屏
        SetWindowPos(windowHandle, HWND_TOPMOST, 0, 0, Screen.currentResolution.width, Screen.currentResolution.height, SWP_SHOWWINDOW);

        //设置黑色为透明键
        SetLayeredWindowAttributes(windowHandle, 0x00000000, 255, LWA_COLORKEY);
    }
}

2、创建空物体挂载脚本,运行时会将纯黑色的地方透明,并可以对底下其他程序窗体进行操作

3、对MainCamera进行设置,Camera下的Clear Flags设置为Solid Color,Background设置为纯黑色

4、发布运行效果如下


网站公告

今日签到

点亮在社区的每一天
去签到