一个form 名 form1
唯一事件
Private Sub Form_Load()
Module1.creaeteSendThread
msgBox "here!"
End Sub
///////////////////////////////////////
一个Moduels 名 Moduel1Public Declare Function CreateThread Lib "kernel32" (lpThreadAttributes As Any, ByVal dwStackSize As Long, ByVal lpStartAddress As Long, ByVal lpParameter As Long, ByVal dwCreationFlags As Long, lpThreadId As Long) As Long
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)Public Const SLEEP_TIME = 2000Public Function doSendMessage()
While True
MsgBox "msg"
Sleep (SLEEP_TIME)
Wend
End FunctionPublic Function creaeteSendThread()
Dim hThread As Long
Dim ThreadID As Long
hThread = CreateThread(0, 0, doSendMessage, 0, 0, ThreadID)
End Function
为什么Form加载不了了?即程序执行子线程,而msgBox "here!"不执行.
唯一事件
Private Sub Form_Load()
Module1.creaeteSendThread
msgBox "here!"
End Sub
///////////////////////////////////////
一个Moduels 名 Moduel1Public Declare Function CreateThread Lib "kernel32" (lpThreadAttributes As Any, ByVal dwStackSize As Long, ByVal lpStartAddress As Long, ByVal lpParameter As Long, ByVal dwCreationFlags As Long, lpThreadId As Long) As Long
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)Public Const SLEEP_TIME = 2000Public Function doSendMessage()
While True
MsgBox "msg"
Sleep (SLEEP_TIME)
Wend
End FunctionPublic Function creaeteSendThread()
Dim hThread As Long
Dim ThreadID As Long
hThread = CreateThread(0, 0, doSendMessage, 0, 0, ThreadID)
End Function
为什么Form加载不了了?即程序执行子线程,而msgBox "here!"不执行.
While True
MsgBox "msg"
Sleep (SLEEP_TIME)
Wend
End Function
始终在运行,不出来了。
i=i+1
form1.caption=i
loop运行应该就能看到效果了(应该要编译再运行吧,IDE里好象总是单线程的)祝你好运:)
Private Sub Command1_Click() ’取消原Form_Load,换成两按钮
Module1.creaeteSendThread
End SubPrivate Sub Command2_Click()
Debug.Print "here! here! here! here!"
End SubPublic Function doSendMessage() ‘IN Moduel1
While True
Debug.Print "msg"
Sleep (SLEEP_TIME)
DoEvents '此处加一句,为了调试用
Wend
End Function
Command1启动线程后,你可以多次点击Command2,甚至可以关闭form,你的线程依然运行。
================================================
一点议论:
在VB里能否实现多线程,争论很多,我持赞成态度。但你的例程竟然没有发现类模块,那就过于简单了。
简易的线程其属性则不完整,如:线程建立,挂起,通信,消亡...。首先,线程通信机制不建立。这样你无法控制它,但在实验程序中,缺省也无可厚非,但看起来有死机的感觉。
其次,线程的挂起或休眠。你采用了sleep,别以为能像在delphi里可以在模块中调试线程。在模块中SLEEP不起泡的(不起到真正挂起线程,然后等待唤醒),在类模块则有效。
如果一定要在Moduel1里实现挂起,那你得动手写一个YourSleep函数,而不用API,正如我上面添加DOEVENTS,这也只为了观察而已。