xamarinsendkeysxamarin.mac

SendKeys for Xamarin.Mac


I am building a Mac app in Xamarin and have a need to send keystrokes (with words and phrases) to other applications. Something like SendKeys in .Net on Windows.

Is there a SendKeys equivalent API for Mac in Xamarin?


Solution

  • CGEventCreateKeyboardEvent is what you are looking for, it is Quartz-based and thus a low-level C API.

    Xamarin has a shim-wrapper over it via an CGEvent .ctor. After you create the event, include any-keyboard modifiers (shift/apple/alt/....), you can Post it to a process id of your choosing.

    Really quick example that sends stackoverflow to active process/window.

    using (var eventSource = new CGEventSource(CGEventSourceStateID.HidSystem))
    {
        var eventString = "StackOverflow";
        foreach (var eventChar in eventString)
        {
            // 🍣 my most favorite Enum.Parse line ever written 🍣
            var key = (ushort)(NSKey)Enum.Parse(typeof(NSKey), eventChar.ToString().ToUpper());
    
            using (var keyEvent = new CGEvent(eventSource, key, true))
            {
                CGEvent.Post(keyEvent, CGEventTapLocation.HID);
            }
        }
    }
    

    Note: To see it in action, place a Task.Delay before it, run it and then switch to/activate an editor, maybe Visual Studio for Mac :-) and let it type into the active editor panel.

    FYI: You might want to refer to the Xamarin wrapper/source code for CGEvent.cs, as their naming is not vary ObjC or Swift friendly in terms of be able from translate Apple docs to Xamarin.Mac code.

    Re: xamarin-macios/src/CoreGraphics/CGEvent.cs