include win32lib.ew
without warning

atom jk,flag
flag=0

constant
--WH_CBT = 5,-- already defined.
HCBT_ACTIVATE=5,
HCBT_CLICKSKIPPED=6,
HCBT_CREATEWND=3,
HCBT_DESTROYWND=4,
HCBT_KEYSKIPPED=7,
HCBT_MINMAX=1,
HCBT_MOVESIZE=0,
HCBT_QS=2,
HCBT_SETFOCUS=9,
HCBT_SYSCOMMAND=8,
zSetWindowsHookEx=registerw32Function(user32,"SetWindowsHookExA",
  { C_INT,C_INT,C_INT,C_INT},C_INT ),
zUnhookWindowsHookEx=registerw32Function(user32,"UnhookWindowsHookEx",
  { C_INT },C_INT ),
zGetCurrentThreadId=registerw32Function(kernel32,"GetCurrentThreadId",
  {},C_INT )

constant
win=create(Window,"'hooking' threads",0,0,0,300,280,0),
dat=create(LText,"",win,5,5,140,20,0),
dat2=create(LText,"",win,5,25,140,20,0),
dat3=create(LText,"",win,150,5,140,20,0),
dat4=create(LText,"",win,150,25,140,20,0),
dat5=create(LText,"",win,5,45,140,20,0),
button=create(PushButton,"About",win,115,190,60,30,0)

setFont(button,"System",10,0)
showWindow(win,SW_NORMAL)
atom threadid
threadid=w32Func(zGetCurrentThreadId,{} )
setText(dat,sprintf("thread_id = %x",{threadid}))

function dummy(atom message,atom wParam,atom lParam)
atom msg_pos,mem,
left,top,right,bottom,new_x,new_y
sequence main_pos
msg_pos=0
main_pos={}
if flag=0 then
if message = HCBT_ACTIVATE then 
setText(dat3,"call_back ...got here !")
setText(dat4,sprintf("message-box_id = %x",{wParam}))
main_pos=getWindowRect(win)
mem=acquire_mem(0,16)
msg_pos=w32Func(xGetWindowRect,{wParam,mem})
left=peek4u(mem)
top=peek4u(mem+4)
right=peek4u(mem+8)
bottom=peek4u(mem+12)
release_mem(mem)
new_x=((main_pos[3]+main_pos[1])/2)-((right-left)/2)
new_y=((main_pos[4]+main_pos[2])/2)-((bottom-top)/2)
jk=w32Func(xMoveWindow,{wParam,new_x,new_y,right-left,bottom-top,1})
flag=1
end if
end if
return NULL
end function
constant fake=call_back(routine_id("dummy"))

atom hook
hook=w32Func(zSetWindowsHookEx,{ WH_CBT, fake, NULL, threadid } )
setText(dat2,sprintf("hook_id = %x",{hook}))

procedure go()
jk=w32Func(zUnhookWindowsHookEx, {hook} )
setText(dat5,sprintf("unhook_success %x",{jk}))
sleep(2)
end procedure
onClose[win]=routine_id("go")

procedure message()
flag=0
jk = message_box( "This message box should open\n" &
"< centered >  over the application",
  "... a thread 'hooking' demo.",#2000)
if jk = IDOK then
setText(dat3,"")
setText(dat4,"")
end if
end procedure
onClick[button]=routine_id("message")

WinMain(win,Normal)
