Issue
I'm trying to subscribe to the Activate event of an NSStatusBarButton object in AppDelegate's DidFinishLaunching() but the event never gets invoked.
The purpose is to get notified when the top menu bar icon of the application is clicked so its contents can get populated dynamically.
using AppKit;
using Foundation;
[Register("AppDelegate")]
public class AppDelegate : NSApplicationDelegate
{
private NSStatusItem _statusBar;
public override void DidFinishLaunching(NSNotification notification)
{
this._statusBar = NSStatusBar.SystemStatusBar.CreateStatusItem(NSStatusItemLength.Variable);
this._statusBar.Title = "MyApp";
this._statusBar.HighlightMode = true;
this._statusBar.Menu = new NSMenu("MyApp");
// Working example on NSMenuItem object
var someItem = new NSMenuItem("Some Item");
someItem.Activated += (sender, e) =>
{
System.Diagnostics.Debug.WriteLine("This one does fire.");
};
this._statusBar.Menu.AddItem(someItem);
// Problem
this._statusBar.Button.Activated += (sender, e) =>
{
System.Diagnostics.Debug.WriteLine("This one does not fire.");
};
}
}
Solution
It does not fire because you attached a menu. The button action is popping up the menu and the activated event of the button is never fired. If you remove the menu the button event will run.
Either remove the menu and use it as a button. Then your event will fire. Or just use the menu.
If you want to run custom code when the menu is shows set a delegate of the NSMenu:
using AppKit;
using Foundation;
public class MyMenuDelegate : NSObject, INSMenuDelegate
{
public void MenuWillHighlightItem(NSMenu menu, NSMenuItem item)
{
}
[Export("menuWillOpen:")]
public void MenuWillOpen(NSMenu menu)
{
// your code here
}
}
[Register("AppDelegate")]
public class AppDelegate : NSApplicationDelegate
{
private NSStatusItem _statusBar;
MyMenuDelegate _menuDel;
public override void DidFinishLaunching(NSNotification notification)
{
_statusBar = NSStatusBar.SystemStatusBar.CreateStatusItem(NSStatusItemLength.Variable);
_statusBar.Title = "MyApp";
_statusBar.HighlightMode = true;
_statusBar.Menu = new NSMenu("MyApp");
_menuDel = new MyMenuDelegate();
_statusBar.Menu.Delegate = _menuDel;
// Working example on NSMenuItem object
var someItem = new NSMenuItem("Some Item");
someItem.Activated += (sender, e) =>
{
System.Diagnostics.Debug.WriteLine("This one does fire.");
};
_statusBar.Menu.AddItem(someItem);
}
}
Answered By - svn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.