WaitForSingleObject appears to fail

BlitzMax Forums/BlitzMax Programming/WaitForSingleObject appears to fail

Blueapples(Posted 2007) [#1]
I've written a quick function to wait for a process to end, given part of it's name. Looks like this:

Const SYNCHRONIZE:Int = 1048576
Const STANDARD_RIGHTS_REQUIRED:Int = 983040
Const INFINITE:Int = $FFFF

Extern "Win32"
	Function WinExec(lpCmdLine:Byte Ptr,nCmdShow:Int)="WinExec@8" 
	Function GetTickCount:Int()="GetTickCount@0"
	Function CreateToolhelp32Snapshot:Int(lFlags:Int, lProcessID:Int)
	Function Process32First(hSnapShot:Int, uProcess:Byte Ptr)
	Function Process32Next(hSnapShot:Int, uProcess:Byte Ptr)
	Function EnumWindows(lpEnumProc:Byte Ptr, lParam:Int)
	Function GetWindowThreadProcessId:Int(HWnd:Int, lpdwProcessID:Int Ptr)
	Function CloseWindow:Int(hWnd:Int)
	Function GetWindowText:Int(hWnd:Int, lpString:Byte Ptr, nMaxCount:Int) = "GetWindowTextA@12"
	Function TerminateProcess:Int(processhandle:Int, exitcode:Int)
	Function GetClassName(hWnd:Int, clString:Byte Ptr, nMaxCount:Int) = "GetClassNameA@12"
	Function SetWindowLong:Int(hwnd:Int,index:Int,value:Int)="SetWindowLongA@12"
	Function GetWindowLong:Int(hWnd:Int, index:Int)="GetWindowLongA@8"
	Function WaitForSingleObject:Int(hHandle:Int, dwMilliseconds:Int)
	Function OpenProcess:Int(dwDesiredAccess:Int, bInheritHandle:Int, dwProcessId:Int)
	Function CloseHandle:Int(hObject:Int)
End Extern


Function WaitProcessEx:Int(ProcessName:String)
	Local Result:Int = False
	Local ProcessID:Int
	Local hProcess:Int
	
	ProcessID = FindProcessEx(ProcessName)
	hProcess = OpenProcess(SYNCHRONIZE, False, ProcessID)
	Notify "Process handle of " + ProcessName + "(" + String.FromInt(ProcessID) + ") = " + String.FromInt(hProcess)
	WaitForSingleObject(hProcess, INFINITE)
	CloseHandle(hProcess)
End Function

Function FindProcessEx:Int(ProcessName:String)
	' Return process ID, or true if no id available on the platform but process is running
	Local Result:Int = 0
	ProcessName = ProcessName.ToUpper()
	Local p:PROCESSENTRY32 
	Local h:Int
	
	p:PROCESSENTRY32 = New PROCESSENTRY32
	p.dwSize = SizeOf(processentry32)
	h:Int = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
	
	Process32First(h,p)
	While Process32Next(h,p)
		If String.FromCString(Varptr p.szExeFile).ToUpper().Find(ProcessName) > -1 Then
			'Notify "Process " + ProcessName + " found as " + String.FromCString(Varptr p.szExeFile).ToUpper()
			Result = p.th32ProcessID
			Exit
		End If
	Wend
	CloseHandle(h)
	
	Return Result
End Function


The FindProcessEx() function works just fine, but for some reason WaitForSingleObject() seems to be returning immediately. Does anyone know more about this and can tell me what I'm doing wrong?

EDIT: Figured out what I was doing wrong, the call to OpenProcess() had the wrong security constant, I was using STANDARD_RIGHTS_REQUIRED when it requires SYNCHRONIZE. Fixed it in the code above.

I hope someone finds the (corrected) code useful.