LoadPicture - appears not to release the file once run.

Issue #84 closed
Winter Laite created an issue

ISSUE:

Apparently in Keysharp LoadPicture does not release the file handle for the picture loaded, while in AHK it does.

This AHK script will use LoadPicture to load an image, create a control, wait a bit, display the picture, then delete the loaded file.

MyGui := Gui()
MyScLabel := MyGui.Add("Text", "w300", "Get image from desktop and display")
MyScBtn := MyGui.Add("Button", "w300 h25 x10 y+10 +Default", "Press to load image").OnEvent("Click", GetClip)

MyGui.Show("w350 h350")

GetClip(*) {

    MyPic := LoadPicture(A_Desktop "\MyScreenClip.png")
    MyLoadedPic := MyGui.Add("Picture", "x10 y50 w200 h200", "HBITMAP:" MyPic)
    Sleep(2000)

    DllCall("DestroyWindow", "Ptr", MyLoadedPic.Hwnd)
    MyPic := ""
    FileDelete(A_Desktop "\MyScreenClip.png")

}

This very similar Keysharp script tries to do the same thing:

MyGui := Gui()
MyScLabel := MyGui.Add("Text", "w300", "Get screenclip at 100, 100, 200, 200`nSave to Desktop as '\MyScreenClip.bmp")
MyScBtn := MyGui.Add("Button", "w300 h25 x10 y+10 +Default", "Press to get screenclip").OnEvent("Click", "GetClip")

MyGui.Show("w350 h350")

GetClip() {
    If !(FileExist(A_Desktop "\MyScreenClip.png")) {
        GetScreenClip(100, 100, 200, 200, A_Desktop "\MyScreenClip.png")
        Sleep(100)
    }
    MyPic := LoadPicture(A_Desktop "\MyScreenClip.png")
    MyLoadedPic := MyGui.Add("Picture", "x10 y50 w200 h200", "HBITMAP:" MyPic["Handle"])
    Sleep(2000)

    DllCall("DestroyWindow", "Ptr", MyLoadedPic.Hwnd)
    FileDelete(A_Desktop "\MyScreenClip.png")
}

But there is an unhandled exception:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. 
Message: Failed 1 times moving or copying files. What: Keysharp.Core.File.FileDelete()

For smoke testing the ‘FileDelete' line was removed from both scripts.

While the AHK script is running, once the control has been destroyed the file can be deleted.

With Keysharp it cannot be deleted, Windows reports the file is still open in Keysharp (even though the control holding the image loaded has been destroyed).

Comments (4)

  1. Matt Feemster repo owner

    I’ve committed a fix which ensures the file is not locked after loading. Please test.

    Remove the call to DestroyWindow. I will add the ability to destroy and remove a control later on.

  2. Log in to comment