【问题标题】:How to capture mouse events in C# MonoMac如何在 C# MonoMac 中捕获鼠标事件
【发布时间】:2015-05-20 10:22:17
【问题描述】:

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

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

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 类中。所以我创建了 NSView 类:

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) { }

谢谢你的帮助

【问题讨论】:

    标签: c# xamarin mono nswindow monomac


    【解决方案1】:

    你不需要 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 2023-03-19
      • 2012-12-16
      • 1970-01-01
      相关资源
      最近更新 更多