在macOS下,可以使用以下代码实现在桌面上覆盖一个无边框窗口:

import Cocoa

class AppDelegate: NSObject, NSApplicationDelegate {

    var window: NSWindow!
    var viewController: NSViewController!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // 创建一个窗口
        window = NSWindow(contentRect: NSMakeRect(0, 0, NSScreen.main!.frame.width, NSScreen.main!.frame.height), styleMask: .borderless, backing: .buffered, defer: false)
        window.backgroundColor = .clear
        window.alphaValue = 1.0
        window.isOpaque = false
        window.level = .desktop
        window.collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle]

        // 创建一个视图控制器
        viewController = NSViewController()
        window.contentViewController = viewController

        // 在视图控制器中添加一个视图
        let view = NSView(frame: NSMakeRect(0, 0, NSScreen.main!.frame.width, NSScreen.main!.frame.height))
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.clear.cgColor
        viewController.view = view

        // 显示窗口
        window.makeKeyAndOrderFront(nil)
    }
}

let appDelegate = AppDelegate()
NSApplication.shared.delegate = appDelegate
NSApplication.shared.run()

以上代码会创建一个全屏的无边框窗口,并将窗口级别设置为桌面级别(.desktop),这使得该窗口在桌面上覆盖所有其他窗口。同时,该窗口的 collectionBehavior 属性被设置为 .canJoinAllSpaces.stationary.ignoresCycle,以便在桌面上的所有空间中保持稳定和不可见。最后,一个空的视图被添加到视图控制器中,并被设置为窗口的 contentViewController

如何用代码实现macOS下的桌面上覆盖一个无边框窗口类似于windows上的wallpaper engine

原文地址: https://www.cveoy.top/t/topic/fUTA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录