1,066
社区成员
发帖
与我相关
我的任务
分享
Private Declare Function CreateThread Lib "Kernel32.dll" (ByVal lpThreadAttributes As Long, ByVal dwStackSize As Long, ByVal lpStartAddress As Long, ByVal lpParameter As Long, ByVal dwCreationFlags As Long, lpThreadId As Long) As Long
Private Declare Function TerminateThread Lib "Kernel32.dll" (ByVal hThread As Long, ByVal dwExitCode As Long) As Long
Private Declare Function CloseHandle Lib "Kernel32.dll" (ByVal hObject As Long) As Long
Dim hThread1 As Long
Dim idThread1 As Long
Dim hThread2 As Long
Dim idThread2 As Long
Dim td1 As vbThreadData
Dim td2 As vbThreadData
Private Sub Form_Load()
td1.ProgId = "aatest1.Class1"
td1.param1 = 1
hThread1 = vbCreateThread(td1, idThread1)
td2.ProgId = "aatest1.Class1"
td2.param1 = 2
hThread2 = vbCreateThread(td2, idThread2)
MsgBox "线程1:" & hThread1 & " " & idThread1 & vbCrLf & "线程2:" & hThread2 & " " & idThread2
End Sub
Private Sub Form_Unload(Cancel As Integer)
TerminateThread hThread1, 0
CloseHandle hThread1
End Sub
Private Sub Timer1_Timer()
Text1.Text = td1.ProgId
Text2.Text = td1.param1
Text3.Text = td2.ProgId
Text4.Text = td2.param1
Text5.Text = td2.param1 - td1.param1
End Sub
Option Explicit
Implements IThread
Private Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
Private Function IThread_Start(threadData As TLb_IvbThread.vbThreadData) As Long
Dim i As Long
MsgBox "IThread_Start: " & threadData.ProgId & " " & threadData.param1
For i = 0 To 1000000
threadData.param1 = i
threadData.ProgId = Now
Sleep 1
Next
End Function
DWORD WINAPI ThreadStartRoutine(LPVOID lpThreadParameter)
{
HRESULT hr;
long exitCode=0;
CComPtr<IDispatch> clsptr;
vbThreadData *threadData=(vbThreadData *)lpThreadParameter;
hr=CoInitialize(0);
hr=clsptr.CoCreateInstance(threadData->progId);
if (SUCCEEDED(hr))
{
IThread *pIThread=0;
hr=clsptr->QueryInterface(&pIThread);
if (SUCCEEDED(hr))
{
hr=pIThread->Start(threadData,&exitCode);
pIThread->Release();
}
else MessageBox(0,TEXT("没有实现 IThread 接口"),TEXT("vbThread"),MB_ICONERROR);
clsptr.Release();
}
else MessageBox(0,TEXT("无法创建实例,请检查 ProgId"),TEXT("vbThread"),MB_ICONERROR);
CoUninitialize();
return (DWORD)exitCode;
}
extern "C" HANDLE WINAPI vbCreateThread(LPVOID lpParameter,LPDWORD lpThreadId)
{
return CreateThread(0,0,ThreadStartRoutine,lpParameter,0,lpThreadId);
}