我有一个这样的程序
let form = new Form()
let drawArea = new Panel(Location = new Point(200,0), Height = 600, Width = 800)
let rectBrush = new SolidBrush(Color.Blue)
form.Controls.Add(drawArea)
drawArea.MouseClick.Add(fun args ->
drawArea.Paint.Add(fun e ->
e.Graphics.FillRectangle(rectBrush, args.X, args.Y, 50, 50)))
Application.Run(form)
因此,当我单击一个蓝色矩形时。但是,这些矩形存储在哪里?有什么方法可以检索“drawArea”中所有矩形的列表?
否则,是否有办法将矩形作为子 Controller 添加到面板或模拟Winform对象?
谢谢
最佳答案
我不知道以这种方式检索这些矩形的方法。
最好的办法是制作一个Rectangle类,并使它继承自Control或UserControl。然后重写它 protected OnPaint(...)方法。例如:
public class FilledRectangle : UserControl
{
private readonly float x, y, w, h;
// also the brush here
public FilledRectangle(float x, float y, float w, float h)
{
this.x = x;
// ...
}
protected override void OnPaint(PaintEventArgs e) // not sure about the event args type name
{
e.Graphics.FillRectangle(this.myBrush, this.x, this.y, this.w, this.h);
}
}
现在,您可以简单地将此类型的对象添加到Controls集合中,如下所示:
Controls.Add(new FilledRectangle(...));
使用这种方法,您可以轻松创建矩形对象的集合,并使它们的行为像您希望的那样。
请注意,我上面编写的示例在C#中进行,但是将其移植到F#并不难。我不这样做的唯一原因是因为我对它的语法不是很熟悉。您的问题不是特定于F#,而是特定于.NET。
还要注意,正如汉斯(Hans)所说,在您调用Invalidate()之前,不会触发Paint事件。
关于winforms - F#和Winforms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8727861/