winforms – 在F#中使用Windows窗体的面向对象的“Hello world”

我目前正在通过“真实世界的功能编程”.我试图让1.12工作,一个使用 Windows窗体的“hello world”程序.这是代码: –
open System.Drawing;;
    open System.Windows.Forms;;

    type HelloWindow() =
         let frm = new Form(Width = 400,Height = 140)
         let fnt = new Font("Times New Roman",28.0f)
         let lbl = new Label(Dock = DockStyle.Fill,Font = fnt,TextAlign = ContentAlignment.MiddleCenter)
         do frm.Controls.Add(lbl)


         member x.SayHello(name) =
              let msg = "Hello" + name + "!"
              lbl.Text <- msg

         member x.Run() =
              Application.Run(frm);;

    let hello = new HelloWindow();;
    hello.SayHello("you");;
    hello.Run();;

不幸的是,这会引发错误 – “在单个线程上启动第二个消息循环不是有效的操作.”显然,有一个窗口打开而不是终止,这使程序混乱.我看不出如何修复错误,任何人都可以帮助我吗?

我也尝试输入最终的代码块: –

let hello = new HelloWindow()
    hello.SayHello("you")
    hello.Run();;

但这没有用.代码运行正常但没有结果,最后一行被注释掉了.

该示例旨在编译并作为Windows窗体应用程序运行.如果您想在F#Interactive中运行它,则必须使用frm.Show()而不是Application.Run(frm).

您可以使用compiler directives在F#Interactive和编译项目中使示例工作:

type HelloWindow() =
    let frm = new Form(Width = 400,Height = 140)
    // ...
    // The same as before

    member x.Run() =
        #if INTERACTIVE
        frm.Show()
        #else
        Application.Run(frm)
        #endif

相关文章

文章浏览阅读2.2k次,点赞6次,收藏20次。在我们平时办公工作...
文章浏览阅读1k次。解决 Windows make command not found 和...
文章浏览阅读3.2k次,点赞2次,收藏6次。2、鼠标依次点击“计...
文章浏览阅读1.3w次。蓝光版属于高清版的一种。BD英文全名是...
文章浏览阅读974次,点赞7次,收藏8次。提供了更强大的功能,...
文章浏览阅读1.4w次,点赞5次,收藏22次。如果使用iterator的...