Jump to content
Sign in to follow this  
Guest pierre

mutex UDF

Recommended Posts

Guest pierre

This sample code is handy to prevent two scripts from running at the same time.

You just have to use a unique GUID as parameter to CreateMutex.

Maybe a cleaner version could find it's place into process.au3 ?

#include <constants.au3>

AutoItSetOption ("MustDeclareVars", 1)

Global $hMutex
local $errorlevel
Local $closehandle

if CreateMutex("cad77ff0-5d14-11d9-9669-0800200c9a66", $hMutex) then
;;;; Body of program would go here;;;;
 While 1
 $errorlevel = 0
 $closehandle = DllCall("kernel32.dll", "int", "CloseHandle", "long", $hMutex[0])
 $hMutex = ""; Prevent OnAutoItExit() from releasing an uncreated mutex

 msgbox($MB_SYSTEMMODAL + $MB_ICONEXCLAMATION + $MB_OK, "Error", "Don't run multiple " & @ScriptName)
 $errorlevel = 1


func CreateMutex($mutex, byref $hMutex)
 dim $LastError, $closehandle
 dim $retval

 $hMutex = DllCall("kernel32.dll", "long", "CreateMutexA", "ptr", 0, "int", 1, "str", $mutex)
 $LastError = DllCall("kernel32.dll", "long", "GetLastError")

 if $LastError[0] = $ERROR_ALREADY_EXISTS then
  $closehandle = DllCall("kernel32.dll", "int", "CloseHandle", "long", $hMutex[0])
  $retval = 0
  $retval = 1

 return $retval

func OnAutoItExit()
 dim $releasemutex, $closehandle

 if IsArray ($hMutex) then
  $releasemutex = DllCall("kernel32.dll", "int", "ReleaseMutex", "long", $hMutex[0])
  $closehandle = DllCall("kernel32.dll", "int", "CloseHandle", "long", $hMutex[0])

Share this post

Link to post
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
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Create New...