使用WinForms进行F#拖放:控件的DragDrop事件不会调用引用的成员函数

时间:2010-12-10 19:26:34

标签: windows winforms drag-and-drop f#

你知道为什么F#中的DragDrop事件在我的例子中不能正常工作吗?所有其他事件,如DragEnter,DragLeave,DragOver,......都以同样的方式正常工作。

只需编译此代码并进行试用,将文件拖到表单中,然后查看在启动可执行文件的控制台/终端中触发的事件。

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

type MainForm( args: string list ) as this =
    // subclassing
    inherit Form()

    // controls -------------------
    let dragDropImage = new PictureBox()
    // ----------------------------

    // "constructor" (not a real constructor)
    do this.initComponents()
    // link events to specific member function
    do dragDropImage.DragEnter |> Event.add this.onDragEnter
    do dragDropImage.DragDrop |> Event.add this.onDragDrop
    // this syntax don't work either: do dragDropImage.DragDrop.Add(fun _ -> printfn "dragDrop")
    do dragDropImage.DragLeave |> Event.add this.onDragLeave
    do dragDropImage.DragOver |> Event.add this.onDragOver

    member this.initComponents() =
        // main form attributes
        this.Text <- "Averest-GUI"
        this.ClientSize <- new Size(350,230)
        this.StartPosition <- FormStartPosition.CenterScreen
        // drag'n'drop field
        dragDropImage.Size <- new Size(330,210)
        dragDropImage.Location <- new Point(7,7)
        dragDropImage.AllowDrop <- true // allow Drag'n'Drop functionality
        // insert controls into MainForm
        this.Controls.Add(dragDropImage)

    member this.onDragLeave( e: EventArgs ) =
        printfn "DragLeave" //e.Effect <- DragDropEffects.Copy

    member this.onDragOver( e: DragEventArgs ) =
        printfn "DragOver" //e.Effect <- DragDropEffects.Copy

    member this.onDragEnter( e: DragEventArgs ) =
        printfn "DragEnter" //e.Effect <- DragDropEffects.Copy

    member this.onDragDrop( e: DragEventArgs ) =
        printfn "DragDrop"


let testForm =
    let temp = new MainForm( ["Test"] )
    temp

// single thread apartment model (interacting with COM components)
[<STAThread>]
do Application.Run(testForm)

1 个答案:

答案 0 :(得分:3)

从onDragEnter中删除评论。除非您将e.Effect设置为其中一个e.AllowedEffects,否则不允许掉落。这也改变了光标。