我试图在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)
受到@FoggyFinder的答案的启发,这就是我现在要讨论的内容:
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)
似乎为我工作,并且在我眼中看起来更合适。我现在会将其标记为公认的解决方案,但是我仍然对可能的改进或其他主张感兴趣。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句