-- start demo --
include win32lib.ew
atom ptr, ptr2, ok, proghwnd

constant
    -- new functions !
    zCreateSemaphore = registerw32Function( kernel32, "CreateSemaphoreA", {C_POINTER, C_INT, C_INT, C_POINTER}, C_INT ), 
    zGetLastError = registerw32Function( kernel32, "GetLastError", {}, C_INT ), 
    zBeep = registerw32Function( user32, "MessageBeep", {C_INT}, C_INT ), 
    zERROR_ALREADY_EXISTS = 183

    ptr = allocate_string( "Win32Lib AppWindow 1" ) -- classname
    ptr2 = allocate_string( "..using a semaphore" ) -- title
    -- first, try and find a window using:
    -- classname and title, as in above strings, 
    -- *before* we create THIS window. 
    proghwnd = w32Func( xFindWindow, { ptr, ptr2 } )

constant
Win = create( Window, "..using a semaphore", 0, Default, Default, 300, 100, 0 )

procedure check_self( integer self, integer event, sequence params )

    -- create a semaphore for this instance, using pointer to classname
    ok = w32Func( zCreateSemaphore, {NULL, 0, 1, ptr} )
    ok = w32Func( zGetLastError, {} )
    if ok = zERROR_ALREADY_EXISTS then 
        ok = w32Func( zBeep, { 0 } )
        setText( Win, "..semaphore found !" )
        -- just to test, lets see/report this instance for 3 seconds...
        setVisible( Win, 1 )
        setFont( Win, "System", 10, 1 )
        setPenPos( Win, 1, 1 )
        wPuts( Win, "...another instance found,  so good-bye." )
        sleep( 3 )
        -- set focus to first instance
        ok = w32Func( xSetForegroundWindow, {proghwnd} )

        abort( 0 ) -- and quit.

    end if
    
end procedure
setHandler( Win, w32HOpen, routine_id( "check_self" ) )
------------------------------------------------------


WinMain( Win, Normal )

-- end demo --

