Jump to content

LockFile Function


Jango
 Share

Recommended Posts

Try if this works for you, then I'll create a UDF of it ^_^...

#include <winapi.au3>

$File = @ScriptDir & '\test.txt'

$hFile = _WinAPI_CreateFile($File,2,2,2)

DllCall("Kernel32.dll", "hwnd", "LockFile", "hwnd", $hFile, "dword", 1, "dword", 0, "dword", 1, "dword", 0)

while MsgBox(0,'','File Locked') <> 1
    sleep(10)
WEnd

_WinAPI_CloseHandle($hFile)

while MsgBox(0,'','File Unlocked') <> 1
    sleep(10)
WEnd

or this, even easier :) ...

$File = @ScriptDir & '\test.txt'

$hFile = FileOpen($File,1)

DllCall("Kernel32.dll", "hwnd", "LockFile", "hwnd", $hFile, "dword", 1, "dword", 0, "dword", 1, "dword", 0); Set file lock

FileWriteLine($hFile,"line1")
FileWriteLine($hFile,"line2")
FileWriteLine($hFile,"line3")

while MsgBox(0,'','File Locked') <> 1
    sleep(10)
WEnd

FileClose($hFile); unlocks file

while MsgBox(0,'','File Unlocked') <> 1
    sleep(10)
WEnd

but strange :) dllcall returns 0, _WinAPI_GetLastErrorMessage() returns 'The handle is invalid.'... but the file is locked for me anyhow :huh2: ...

Edited by KaFu
Link to comment
Share on other sites

Ah, okay, I see why _WinAPI_GetLastErrorMessage() returns the error, cause the dllcall isn't working at all :).

$hFile = FileOpen($File,1)

is totally sufficient to lock the file. Open a handle if you want it locked and close it if you want the file locked, that's all.

Link to comment
Share on other sites

If you want to lock the whole file you can just open it with iShare set to 0. If you do want the file to be accessible but to lock only parts of it you can use LockFileEx, but the function returns BOOL (int) rather than hwnd.

Thank you. To learn, this is really a nice forum with nice people.

Link to comment
Share on other sites

If you want to lock the whole file you can just open it with iShare set to 0. If you do want the file to be accessible but to lock only parts of it you can use LockFileEx, but the function returns BOOL (int) rather than hwnd.

Nice to know :)... does Fileopen set iShare to 0? Seems so to me.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...