Mouse Click in Mac OS & Detect Which OS Application is Running in

1.9k views Asked by At

I want to use Mono to allow my C# program (currently WPF but will change it to Windows Forms or Silverlight so that Mono will work) that currently works in Windows to work on a Mac.

I use native windows code to detect when a mouse is clicked, and also to click the mouse, like so:

[DllImport("user32.dll")]
static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
[DllImport("User32.dll")]
public static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey);

In order for this to work on a Mac I need to first be able to detect whether the program is running on a Mac or in Windows, and then run the appropriate code for detecting whether a mouse is clicked, or for clicking the mouse. Something like:

if (runningInWindows())
{
    // Windows mouse click...
    System.Windows.Forms.Cursor.Position = new System.Drawing.Point(X, Y);
    mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
    mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);

    // Or if I want to detect a mouse click...
    bool mouseClicked = GetAsyncKeyState(System.Windows.Forms.Keys.LButton) != 0;
}
else
{
    // Running on a Mac, so do Mac mouse click...
    // Or detect a mouse click on a Mac...
}

Essentially I have 3 questions:

  1. How do you click the mouse on a Mac? (equivalent of mouse_event)
  2. How do you detect a mouse click on a Mac? (equivalent of GetAsyncKeyState)
  3. How do you detect which Operating System your application is running in?
1

There are 1 answers

0
Mikayla Hutchinson On BEST ANSWER

Detecting the operating system is easy, you can find some platform detection code here.

The other two are harder. You'd have to look at Apple's native Carbon or Cocoa APIs and figure out how to do the things you want, then P/Invoke those APIs. FWIW, I don't know whether it's actually possible to control the mouse with public API. There do seem to be some sites around that explain how to do some of this stuff.

For a start, getting the mouse position seems to be possible via HIGetMousePosition (Carbon) or [NSEvent mouseLocation] (Cocoa). Although a lot of high-level Carbon APIs are deprecated, it still forms the core of the low-level C API used by Cocoa. It could be tricky figuring out how to read Carbon events and extract information from them, OTOH Cocoa means interop with Objective-C, which is more complicated than P/Invoke - but MonoMac has some APIs that can make that easier.