Option Explicit
Public Declare Function CreateThread Lib "kernel32" _
(ByVal lpThreadAttributes As Long, _
ByVal dwStackSize As Long, _
ByVal lpStartAddress As Any, _
ByRef lpParameter As Any, _
ByVal dwCreationFlags As Long, _
ByRef lpThreadId As Long) As Long
Public Declare Function CreateThread_ByValParam Lib "kernel32" _
Alias "CreateThread" _
(ByVal lpThreadAttributes As Long, _
ByVal dwStackSize As Long, _
ByVal lpStartAddress As Any, _
ByVal lpParameter As Long, _
ByVal dwCreationFlags As Long, _
ByRef lpThreadId As Long) As Long
' So you can determine which thread the code is executing in.
Public Declare Function GetCurrentThreadId Lib "kernel32" () As Long
' This is the type that is passed to DaThreadFunc so you can do the by
' reference demonstration.
Type PARAM_TYPE
lValue As Long
End Type
' The function used to show a pass by reference.
Function DaThreadFunc(ByRef lpParam As PARAM_TYPE) As Long
Dim szStr As String
szStr = "From DaThreadFunc - Parameter = " & _
CStr(lpParam.lValue) & vbNewLine & _
"Thread ID: " & CStr(GetCurrentThreadId)
MsgBox szStr, , "Function Cool!"
' Just to make the return value different, I return -2.
DaThreadFunc = -2
End Function
' The subroutine to show pass by value.
' By the way, I noticed that subs always return 0.
Sub DaThreadSub(ByVal lpVoid As Long)
Dim szStr As String
szStr = "From DaThreadSub - Parameter = " & _
CStr(lpVoid) & vbNewLine & _
"Thread ID: " & CStr(GetCurrentThreadId)
MsgBox szStr, , "Sub Cool!"
End Sub
Sub Main()
Dim lRet As Long
Dim lThreadID As Long
Dim stParam As PARAM_TYPE
Dim szStr As String
lThreadID = 0
' Do the call to CreateThread with a by reference parameter.
stParam.lValue = -1
lRet = CreateThread(0, _
0, _
AddressOf DaThreadFunc, _
stParam, _
0, _
lThreadID)
' Do the call to CreateThread with a by value parameter.
lRet = CreateThread_ByValParam(0, _
0, _
AddressOf DaThreadSub, _
-2, _
0, _
lThreadID)
szStr = "From Da Main Thread" & vbNewLine & _
"Thread ID: " & CStr(GetCurrentThreadId)
MsgBox szStr
End Sub