2

I am working on a desktop only .NET MAUI application that targets both Mac and Windows. I need to create Printing Service to communicate with the installed printers on the machine. On Windows i was able to achieve that using System.Drawing.Printing using PrinterSettings.InstalledPrinters property. However I've been strugling to do it on Mac. Since AppKit namespace is not available on Mac, I can't use NSPrinter.PrinterNames property to do so. I need to use low-level objective c messaging to create and use objects at runtime.

I have been following Apple documentation and tried the following:

        [DllImport("/usr/lib/libobjc.dylib", EntryPoint = "objc_msgSend")]
        public static extern IntPtr IntPtr_objc_msgSend(IntPtr receiver, IntPtr selector);

        [DllImport("/usr/lib/libobjc.dylib", EntryPoint = "objc_getClass")]
        public static extern IntPtr objc_getClass(string className);

                IntPtr clsNSPrinter = objc_getClass("NSPrinter");
                IntPtr selPrinterNames = ObjCRuntime.Selector.GetHandle("printerNames");
                IntPtr printerNamesPtr = IntPtr_objc_msgSend(clsNSPrinter, selPrinterNames);
                var printersNSArray = Runtime.GetNSObject<NSArray>(printerNamesPtr);
                var printerNames = NSArray.StringArrayFromHandle(printersNSArray.Handle);
                return printerNames.ToList()

After sending the "printerNames" message to NSPrinter class and converting the Ptr to Object, I got empty list. I have tried sample application using Xamarin.Mac where it has support to AppKit and I've used NSPrinter.PrinterNames and it returns list od four printers, exactly the ones i have installed on the machine.

I have also tried to send "alloc" selector to NSPrinter first and then the selector "printerNames" but that way i got an exception that said: "Unrecognized selector printerNames when sent to class"

0 Answers0