您知道为什么 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)
最佳答案
从 onDragEnter 中删除注释。除非您将 e.Effect 设置为 e.AllowedEffects 之一,否则不允许放置。这也会改变光标。
关于windows - F# 使用 WinForms 拖放 : DragDrop event of a control does not call the referenced member function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4412539/