求助:如何在Xamarin.Mac应用中程序化移动窗口?
Xamarin.Mac桌面宠物窗口随机移动实现方案
核心逻辑
通过NSTimer定时触发窗口位置更新,每次生成屏幕范围内的随机坐标,调用窗口的SetFrame方法完成移动,同时随机设置触发间隔模拟宠物的随机行为。
具体代码实现
以下是在NSWindowController中的完整示例代码:
using AppKit; using Foundation; using CoreGraphics; using System; namespace DesktopPet { public partial class PetWindowController : NSWindowController { private NSTimer _moveTimer; private readonly Random _random = new Random(); public PetWindowController(IntPtr handle) : base(handle) { } [Export("initWithCoder:")] public PetWindowController(NSCoder coder) : base(coder) { } public PetWindowController() : base("PetWindow") { } public override void WindowDidLoad() { base.WindowDidLoad(); // 启动随机移动定时器 StartRandomMove(); } private void StartRandomMove() { // 先销毁旧定时器 _moveTimer?.Invalidate(); // 随机设置1-3秒的触发间隔 double interval = _random.NextDouble() * 2 + 1; _moveTimer = NSTimer.CreateScheduledTimer(interval, PerformRandomMove); } private void PerformRandomMove() { var mainScreen = NSScreen.MainScreen.Frame; var windowSize = Window.Frame.Size; // 计算屏幕内可移动的最大范围,确保窗口不超出屏幕 int maxX = (int)(mainScreen.Width - windowSize.Width); int maxY = (int)(mainScreen.Height - windowSize.Height); // 生成随机坐标 int newX = _random.Next(0, maxX); int newY = _random.Next(0, maxY); // 平滑移动窗口(第二个参数true开启动画) Window.SetFrame(new CGRect(newX, newY, windowSize.Width, windowSize.Height), true); // 重新启动定时器,循环触发 StartRandomMove(); } } }
额外需求快速解决(顺带提你关心的其他问题)
- 去除窗口边框:在
WindowDidLoad中添加Window.StyleMask = NSWindowStyleMask.Borderless; - 窗口置顶:添加
Window.Level = NSWindowLevel.Floating; - 移除顶部菜单:在
AppDelegate的FinishedLaunching方法中设置NSApplication.SharedApplication.MainMenu = null;
内容的提问来源于stack exchange,提问作者Ruben
相关产品推荐
相关产品推荐

