如何在 C# MonoMac 中捕获鼠标事件

How to capture mouse events in C# MonoMac

首先,我的目标是创建实用的(没有控制器或类似的东西,只有一个 class)无边界 NSWindow。在此 window 中,我想跟踪鼠标事件,例如:鼠标按下、鼠标移动。就这么简单。

我需要在 Monomac 项目中使用 Xamarin Studio 在 C# 中执行此操作。我的window超级简单

public class MyWindow : NSWindow
{
    public MyWindow()
        :base(new RectangleF (0, 0, 100, 100), 
            NSWindowStyle.Closable | NSWindowStyle.Resizable | NSWindowStyle.Titled, NSBackingStore.Buffered, 
            false)
    {
        this.StyleMask = NSWindowStyle.Borderless;
        this.MakeKeyAndOrderFront( null );
    }
}

现在,据我所知,我应该将 NSView 添加到带有已声明事件的 NSWindow class 中。所以我创建了 NSView class:

public class MouseTracking : NSView
{
    public NSTrackingArea tracking;

    public override bool AcceptsFirstResponder ()
    {
        return true;
    }

    public override void DrawRect(RectangleF dirtyRect)
    {
        base.DrawRect(dirtyRect);
        var context = NSGraphicsContext.CurrentContext.GraphicsPort;
        var rectangle = new RectangleF (0,0, this.Frame.Width, this.Frame.Height);
        NSColor.Blue.Set ();
        context.FillRect (rectangle);
    }

    public override void UpdateTrackingAreas()
    {
        if (tracking != null)
        {
            this.RemoveTrackingArea(tracking);
            tracking.Release();
        }
        tracking = new NSTrackingArea(this.Frame,NSTrackingAreaOptions.MouseEnteredAndExited | NSTrackingAreaOptions.ActiveAlways ,this, null);
        this.AddTrackingArea(tracking);
    }

    public override void MouseMoved(NSEvent theEvent)
    {
        Console.WriteLine("MouseMoved");
    }

    public override void MouseExited(NSEvent theEvent)
    {
        Console.WriteLine("MouseExitedTest");
    }
}

我的问题是如何将 MouseTracking nsview 添加到 MyWindow 并使这些鼠标事件可用?我在 MyWindow 构造函数中尝试过:

        MouseTracking tracking = new MouseTracking ();
        this.ContentView.AddSubview (tracking);

但是,这不起作用..我只想这样做(WinForms 中的两行):

this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panel1_MouseDown);

private void panel1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { }

谢谢,求助

您不需要 DrawRect 来捕获鼠标事件。您需要构造器:

    public MouseTracking(NSCoder coder)
        :base(coder)
    {
    }

    public MouseTracking(RectangleF frameRect)
        :base(frameRect)
    {
    }

您可能还需要(也许您还不知道)覆盖此标志:

    public override bool AcceptsFirstMouse (NSEvent theEvent)
    {
        return true;
    }

是的,您完全按照您写的方式将 MouseTracking 添加到 MyWindow,因此:

    this.ContentView.AddSubview (tracking);