
using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TransparentWindow : MonoBehaviour {
[DllImport("user32.dll")]
public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);
[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)]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
static extern int SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
private struct MARGINS {
public int cxLeftWidth;
public int cxRightWidth;
public int cyTopHeight;
public int cyBottomHeight;
}
[DllImport("Dwmapi.dll")]
private static extern uint DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS margins);
const int GWL_EXSTYLE = -20;
const uint WS_EX_LAYERED = 0x00080000;
const uint WS_EX_TRANSPARENT = 0x00000020;
static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
const uint LWA_COLORKEY = 0x00000001;
private IntPtr hWnd;
private void Start() {
#if !UNITY_EDITOR
hWnd = GetActiveWindow();
MARGINS margins = new MARGINS { cxLeftWidth = -1 };
DwmExtendFrameIntoClientArea(hWnd, ref margins);
SetWindowLong(hWnd, GWL_EXSTYLE, WS_EX_LAYERED | WS_EX_TRANSPARENT);
//SetLayeredWindowAttributes(hWnd, 0, 0, LWA_COLORKEY);
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, 0);
#endif
}
private void Update() {
if (Input.GetKeyDown(KeyCode.Q))
{
hWnd = GetActiveWindow();
MARGINS margins = new MARGINS { cxLeftWidth = -1 };
DwmExtendFrameIntoClientArea(hWnd, ref margins);
}
if (Input.GetKeyDown(KeyCode.E))
{
hWnd = GetActiveWindow();
MARGINS margins = new MARGINS { cxLeftWidth = 0 };
DwmExtendFrameIntoClientArea(hWnd, ref margins);
}
SetClickthrough(true);
}
private void SetClickthrough(bool clickthrough) {
if (clickthrough) {
SetWindowLong(hWnd, GWL_EXSTYLE, WS_EX_LAYERED | WS_EX_TRANSPARENT);
} else {
SetWindowLong(hWnd, GWL_EXSTYLE, WS_EX_LAYERED);
}
}
}
这篇博客介绍了一个Unity脚本,通过C#调用Windows API实现了窗口透明化和点击穿透功能。用户按下Q键可以使窗口变为全透明,E键则取消透明效果。脚本使用了DllImport特性导入user32.dll和Dwmapi.dll库,设置窗口样式和扩展帧区域来达到效果。
415

被折叠的 条评论
为什么被折叠?



