[英]System Tray only (no dock icon) application using C# / Mono on Mac
[英]How do I make a tray-icon-only C# application in MonoMac (no dock icon)?
我正在嘗試創建一個只有托盤圖標的應用程序,而不會出現在任務欄中。 (類似於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
,圖標就會重新出現在屏幕底部的停靠欄中。 我錯過了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();
}
}
我發現了問題,它與應用程序設置無關。 顯然,有一些操作MacOS不允許“代理應用程序”執行。 只要調用其中一個方法,就會強制應用程序出現在停靠欄中。 絆倒我的應用程序的代碼是調用:
System.Windows.Forms.Cursor.Position.ToString()
刪除該行,並使用以下MonoMac方法替換它,允許應用程序保持隱藏狀態:
NSEvent.CurrentMouseLocation.ToString()
我能夠通過在info.plist文件中將“Application is agent(UIElement)”鍵的值設置為1來實現此功能。 盡管它應該是BOOL值,MonoDevelop使它成為一個字符串,但將其設置為1似乎可行。 您也可以為“圖標文件”設置一個空字符串,但這不是必需的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.