3

As we know, if we press the F8(Play) keyboard button, iTunes or Music .app opened in default on macOS. Some Swift classes are available for preventing this keyboard shortcut but they are not compatible with C# & Xamarin. Fore example, Spotify macOS app have this ability. If you press play button on UI once, it takes the control over iTunes and handles the "Play" button key event.

I have this code block. However, macOS cannot fires the code block because of iTunes. The other keys like letters and numbers working correctly:

private NSEvent KeyboardEventHandler(NSEvent theEvent)
    {


        ushort keyCode = theEvent.KeyCode;


        if(keyCode== 100) //rbKeyF8 100 is play button.
        {
            switch (isplaying)

            {
                case true:
                    StopMusic();
                    break;
                case false:
                    PlayMusic();
                    break;
            }
        }
        //    NSAlert a = new NSAlert()
        //{
        //    AlertStyle = NSAlertStyle.Informational,
        //    InformativeText = "You press the " + keyCode + " button :)",
        //    MessageText = "Hi"

        //};
        //a.RunModal();

        return theEvent;
    }

How can we do it with C# ? Thanks.

berkb
  • 542
  • 6
  • 21
  • You need to override `SendEvent` in your NSApplication class and capture (and process) any NSEvent.SystemDefined events and determine which of the media keys were pressed, etc... I do not have my Xamarin.Mac code handy, but I converted some Swift code originally and also ended up looking at the ObjC code for `SPMediaKeyTap` (on Github). – SushiHangover Nov 13 '19 at 11:43
  • I cannot find to override the SendEvent in both AppDelegate.cs and ViewController.cs. Where I will override it ? Thanks @SushiHangover – berkb Nov 13 '19 at 14:33

1 Answers1

0

Answer is: Register a new subclass

[Register ("App")]
public class App : NSApplication
{
    public App (System.IntPtr p) : base (p)
    {

    }

    public override void SendEvent (NSEvent theEvent)
    {
        base.SendEvent (theEvent);
    }
}

In Info.plist change the PrincipalClass

<key>NSPrincipalClass</key>
<string>App</string>

And need to subclass NSApplication and look at sendEvent. You should convert Swift code to C#. Related swift code is here: Make my Cocoa app respond to the keyboard play/pause key?

Now, i have another problem. Yep, this code block solved my problem’s first part. Now my app responds the play button press. However, iTunes opened after the my app's respond. How can I prevent it to open ?

berkb
  • 542
  • 6
  • 21
  • If iTunes opened after app,s respond , I think they will have some conflicts, and the Mac will give priority to iTunes control. To avoid the same conflicts as iTunes shortcuts, you can try other shortcuts (F6 or Combination shortcut ). – Junior Jiang Nov 15 '19 at 02:16