GetThreadId for windows os

Got an idea for enhancing PureBasic? New command(s) you'd like to see?
dougmo52usr
User
User
Posts: 62
Joined: Mon Jul 18, 2016 6:43 pm

GetThreadId for windows os

Post by dougmo52usr »

Some win32 functions take a ThreadId, ie: PostThreadMessage. MSDN says there is a GetThreadId win32 function, but also says it is Vista or newer. I call GetCurrentThreadId on entry to my thread function to obtain and save the value. If PBs CreateThread called win32s CreateThread under the hood, it had to provide an @ThreadId as one of the parameters passed to win32s CreateThread. It would be great if PB would add a GetThreadId which simply returned the value referenced by the lpThreadId in the win32 CreatThread call.
User avatar
Keya
Addict
Addict
Posts: 1890
Joined: Thu Jun 04, 2015 7:10 am

Re: GetThreadId for windows os

Post by Keya »

dougmo52usr wrote:MSDN says there is a GetThreadId win32 function, but also says it is Vista or newer.
if my understanding was correct the following is exactly what GetThreadId does under the hood, so it should also support pre-Vista - it works fine on my XP which doesnt have GetThreadId, but only NT systems so not Win9x/ME, but its probably time to let those RIP lol.

Code: Select all

#ThreadBasicInformation = 0

Structure CLIENT_ID
  dwPID.l
  dwTID.l
EndStructure

Structure THREAD_BASIC_INFORMATION
  ExitStatus.l
  TebBaseAddress.l
  ClientId.CLIENT_ID
  AffinityMask.l
  Priority.l
  BasePriority.l
EndStructure

Import "ntdll.lib"
  NtQueryInformationThread.i (hThread, THREAD_INFORMATION_CLASS, ThreadInformation, ThreadInformationLen, returnlen)
EndImport

Procedure.i ThreadHandleToId(hThread) ;essentially kernel32!GetThreadId()
  Protected TBI.THREAD_BASIC_INFORMATION, lRet.l
  NtQueryInformationThread(hThread, #ThreadBasicInformation, TBI, SizeOf(TBI), @lRet)
  If lRet: ProcedureReturn TBI\ClientId\dwTID: EndIf
EndProcedure

Define hThread = GetCurrentThread_()  ;thread handle not id
dwThreadID = ThreadHandleToId(hThread)
Debug "ThreadID = " + Hex(dwThreadID)
Post Reply