如何在MonoMac中创建一个只有托盘图标的C#应用程序(没有Dock图标)?

13
我正在尝试创建一个只有托盘图标的应用程序,不会出现在任务栏中(类似于Dropbox)。我需要创建应用程序的Windows和Mac版本,因此我尝试使用MonoMac来创建Mac前端。
在MonoMac中创建仅托盘应用程序的最佳方法是什么?
我找到的所有资源都说要做以下两件事之一: - 将<key>LSUIElement</key><string>1</string>添加到Info.plist文件中。 - 在AppDelegate类的FinishedLaunching事件中添加以下代码:NSApplication.SharedApplication.ActivationPolicy = NSApplicationActivationPolicy.Accessory; 我已经尝试了这两种方法的所有组合,但似乎一旦我尝试实例化C# System.Timers.Timer,图标就会重新出现在屏幕底部的dock中。我是否忽略了OSX如何处理后台应用程序的某些内容?
我做错了什么?在OSX中,有没有更好的方法制作一个具有上层托盘图标但没有底部dock图标的后台应用程序?
(这与SO问题非常相似,但那个问题是几年前的,从未得到完整的答案,因此我希望可能会有更完整的答案。)

这是我目前的代码:

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();
    }
}

我也很想知道答案! - berg
2个回答

7

我找到了问题,它与应用程序设置完全无关。显然,有些操作MacOS不允许“代理应用程序”执行。一旦调用其中一个方法,应用程序就被强制出现在dock中。导致我的应用程序出现问题的代码是调用:

System.Windows.Forms.Cursor.Position.ToString()

删除该行代码并替换为以下的MonoMac方法可以使应用程序保持隐藏:
NSEvent.CurrentMouseLocation.ToString()

3
我能通过在info.plist文件中将“Application is agent (UIElement)”键的值设置为1来使其工作。尽管它应该是一个BOOL值,但MonoDevelop将其变成了一个字符串,但将其设置为1似乎可以工作。您还可以将“Icon file”设置为空字符串,但这并不是必需的。 info.plist

谢谢你的建议 - 我尝试了,但不幸的是没有用。 - Matt
你能分享你的应用程序的更多代码吗?你的info.plist是什么样子的?MyServiceObject是做什么的? - berg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接