使用自定义OnPaint在F#中自定义Windows.Forms控件?

时间:2016-04-09 19:19:10

标签: winforms f# custom-controls

我尝试在F#中实现自定义Windows.Forms控件,但我的“OnPaint”方法似乎根本没有被调用(它没有显示,并且调试消息不会打印到控制台)。我做错了什么?

open System
open System.Drawing
open System.Windows.Forms

let form = new Form(Visible=true, Text="Drawing App", WindowState=FormWindowState.Maximized)

type Canvas() =
    class
        inherit Control()
        override c.OnPaint(e:PaintEventArgs) =
            System.Diagnostics.Debug.WriteLine("OnPaint")
            base.OnPaint(e)
            let g = e.Graphics
            g.DrawLine(Pens.Blue, 0, 0, c.Width, c.Height)
    end

System.Diagnostics.Debug.WriteLine("hello")
let canvas = new Canvas()
canvas.Visible <- true
form.Controls.Add(canvas)

[<STAThread>]
Application.Run(form)

如果我用下面的那个替换“let canvas ...”块,则窗口中会出现 标签:

let label = new Label(Text="sample label")
form.Controls.Add(label)

2 个答案:

答案 0 :(得分:3)

未画线,因为c.Width = c.Height = 0。

设置画布大小并获得结果:

canvas.Size <- Size (form.Width, form.Height)

修改

Canvas大小与表单相同,足以进行事件订阅:

form.SizeChanged.Add(fun e -> canvas.Size <- form.Size; canvas.Refresh())

答案 1 :(得分:1)

@FoggyFinder's answer的启发,这就是我现在所收集的内容:

open System
open System.Drawing
open System.Windows.Forms

let form = new Form(Visible=true, Text="Drawing App", WindowState=FormWindowState.Maximized)

type Canvas() =
    inherit Control()
    override c.OnPaint(e:PaintEventArgs) =
        //System.Diagnostics.Debug.WriteLine("OnPaint")
        base.OnPaint(e)
        let g = e.Graphics
        g.DrawLine(Pens.Blue, 0, 0, c.Width, c.Height)
    override c.OnResize(e:EventArgs) =
        c.Refresh()

let canvas = new Canvas(Dock = DockStyle.Fill)
form.Controls.Add(canvas)

[<STAThread>]
Application.Run(form)

似乎对我有用,看起来更适合我的眼睛。我现在将此标记为可接受的解决方案,但如果可能,我仍然对改进感兴趣,或者其他命题。