You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 13:30:47