如何在MonoMac中制作仅托盘图标的C#应用​​程序(无停靠图标)?

Mat*_*att 13 c# macos mono monomac

我正在尝试创建一个只有托盘图标的应用程序,而不会出现在任务栏中.(类似于Dropbox)我需要创建应用程序的Windows和Mac版本,所以我尝试使用MonoMac来创建Mac前端.

在MonoMac中创建仅托盘应用程序的最佳方法是什么?

我找到的所有资源都说要做两件事之一:

  • 添加<key>LSUIElement</key><string>1</string>Info.plist文件中.
  • 将以下代码添加到类中的FinishedLaunching事件AppDelegate:NSApplication.SharedApplication.ActivationPolicy = NSApplicationActivationPolicy.Accessory;

我已经尝试了这两种的所有组合,但似乎只要我尝试实例化C#System.Timers.Timer,图标就会重新出现在屏幕底部的底座中.我错过了OSX处理后台应用程序的方法吗?

我究竟做错了什么?是否有更好的方法来制作具有上部托盘图标但在OSX中没有底部停靠图标的后台应用程序?

(这与这个问题非常相似,但这个问题来自几年前,并且从未得到完全回答,所以我希望那里可能有更完整的答案.)


这是我到目前为止的代码:

public partial class AppDelegate : NSApplicationDelegate
{
    MyServiceObject currentServiceObject;

    public AppDelegate () { }

    public override void FinishedLaunching (NSObject notification)
    {
        // Construct menu that will be displayed when tray icon is clicked
        var notifyMenu = new NSMenu();
        var exitMenuItem = new NSMenuItem("Quit My Application", 
            (a,b) => { System.Environment.Exit(0); }); // Just add 'Quit' command
        notifyMenu.AddItem(exitMenuItem);

        // Display tray icon in upper-right-hand corner of the screen
        var sItem = NSStatusBar.SystemStatusBar.CreateStatusItem(30);
        sItem.Menu = notifyMenu;
        sItem.Image = NSImage.FromStream(System.IO.File.OpenRead(
            NSBundle.MainBundle.ResourcePath + @"/notify-icon.icns"));
        sItem.HighlightMode = true;

        // Remove the system tray icon from upper-right hand corner of the screen
        // (works without adjusting the LSUIElement setting in Info.plist)
        NSApplication.SharedApplication.ActivationPolicy = 
            NSApplicationActivationPolicy.Accessory;

        // Start running the program -- If I comment out then no dock icon appears
        currentServiceObject = new MyServiceObject();
    }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 7

我发现了问题,它与应用程序设置无关.显然,有一些操作MacOS不允许"代理应用程序"执行.只要调用其中一个方法,就会强制应用程序出现在停靠栏中.绊倒我的应用程序的代码是调用:

System.Windows.Forms.Cursor.Position.ToString()
Run Code Online (Sandbox Code Playgroud)

删除该行,并使用以下MonoMac方法替换它,允许应用程序保持隐藏状态:

NSEvent.CurrentMouseLocation.ToString()
Run Code Online (Sandbox Code Playgroud)