Prevent iTunes / Music.app Start After Pressing F8(Play) Button with C# & Xamarin

berkbababerkbaba TRMember ✭✭
edited November 13 in Xamarin.Mac

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.

Best Answer

Answers

  • ChrisHamonsChrisHamons USForum Administrator, Xamarin Team Xamurai

    It looks like you need to subclass NSApplication and look at sendEvent

    https://stackoverflow.com/questions/3885302/make-my-cocoa-app-respond-to-the-keyboard-play-pause-key

    Apple does not make this easy :(

  • berkbababerkbaba TRMember ✭✭

    I read the Stackoverflow question before. But I have a stuck thought in my mind which is critical:

    How can I create a NSApplication subclass ? In existing classes or should I create a new class ? Not my application is a NSApplication ? How will two NSApplication work at the same time?

    Thanks.

  • berkbababerkbaba TRMember ✭✭

    Thanks ChrisHamons, it solved my problem. Now my app responds the play button press. However, iTunes opened after the my app's respond. How can I prevent it to open ?

  • ChrisHamonsChrisHamons USForum Administrator, Xamarin Team Xamurai

    I don't believe you can mark the event as "handled" give how Cocoa handles NSEvents.

    I'm not sure what APIs exist beyond AppleScript for talking to iTunes.

Sign In or Register to comment.