首先,我的目标是务实创建(没有控制器或类似的东西,只有单一类)无边界的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) { }
谢谢,求助
答案 0 :(得分:0)
您不需要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);