in standard module Public Declare Function SetWindowText Lib "user32" Alias "SetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String) As Longin form private Declare Function SetWindowText Lib "user32" Alias "SetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String) As Long
SetWindowText VB声明 Declare Function SetWindowText Lib "user32" Alias "SetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String) As Long 说明 设置窗口的标题文字或控件的内容(在vb里使用:针对vb窗体,应使用caption或text属性) 返回值 Long,非零表示成功,零表示失败。会设置GetLastError 参数表 参数 类型及说明 hwnd Long,要设置文字的窗口的句柄 lpString String,要设到hwnd窗口中的文字
the code to accomplish this follow, FYIIntro to Multi-Threading in VB Revision 1.0.0 By: AxE ([email protected])===Intro============================================================This is my second text, I don't do spell check, and I don't write a lot. This text is also ment for someone who knows about VB.Multithreading in VB in some cases can be dangerous, and you might need to reboot your system. Who cares though, Windows makes you do that anyway. But still, if you mess up your computer or anything its your own fault. I'm just providing information.===Getting started==================================================In order to multi-thread in VB you need two API calls:Private Declare Function CreateThread Lib "kernel32" (ByVal lpThreadAttributes As Any, ByVal dwStackSize As Long, ByVal lpStartAddress As Long, lpParameter As Any, ByVal dwCreationFlags As Long, lpThreadID As Long) As Long Private Declare Function TerminateThread Lib "kernel32" (ByVal hThread As Long, ByVal dwExitCode As Long) As LongCreateThread will start the thread, and TerminateThread will terminate it.. suprise suprise. Add this global also:Dim id As LongI leave all the control names their defalut names for simplicity. Put all the code listed in this this secion in your form's general declarations.===Setting everything up============================================Add a textbox that is multi-lined and has vertical scroll bars and two command buttons to your form. Label one "Start" and one "Stop"Create a Function, the code should look something like this:Public Function AddText() Do Form1.Text1.SelText = "Adding to Text1 - " Loop End FunctionThis function MUST be in a moduleYou should know not to run this because if you did you would have to kill VB and you would loose your work and have to start over again. This is when multi-threading becomes your best friend. Of corse you will want to use multi-threading for something else, but this is just a example ;)I know this should be a sub too, but multi-threading only works with functions (or so I think, I don't want to "waste time" and try it out, let me know if I'm wrong ;))===Starting a thread================================================This is what your Command1 (Start) button should be coded like:Private Sub Command1_Click() id = CreateThread(ByVal 0&, ByVal 0&, AddressOf AddText, ByVal 0&, 0, id) End SubWe use 'ByVal 0&' because we don't care about those, and just put a NULL value.'AddressOf AddText' will tell the api function where the function you want to multi-thread is located. You can just use the same code and have it go to the address of what ever functions you want to multi-thread.'id' sets the thread number, so you can use it to kill the thread when you are done with it.===Ending a thread==================================================This is what your Command2 (Stop) button should be coded like:Private Sub Command2_Click() Call TerminateThread(id, ByVal 0&) End SubOn creating a thread, you held its PID in the variable id, so you know where it is when you want to kill it.You MUST end a thread before you end your program, otherwise you will have a loose thread running on your computer... thats not good.===Whats going on===================================================You might think this is no big deal, but I dare you to try that function without multi-threading it first! Your program will freeze, and you wont be able to do anything. It will just scroll text in the textbox as it runs. You will have to kill VB to get out of it.For a experiment, add a DoEvents in the loop, and run it wihout multi-threading. You will see that you can click on the tile bar, move it around as you wish, and close it also. But notice how when you do anything else the scrolling of the text will stop? You can only do one thing at a time...Now, when you multithread the function, fun things happen :) If you scroll the window around, you will notice that the text is still being added to the TextBox! The program is now able to do more than one task.Like I said, it might not seem so great right now, but this is just an example... imagine never needing to use DoEvents again, and able to do as many tasks as your CPU can handle at one time... for most compuers now thats a lot of tasks ;)The problem with multi-tasking is, VB still doesnt like multi-taking, so you must compile to run your programs with multi-tasking to run correctly. Most of the time if you run it from VB it will just not go back to the programming part of VB (and you need to kil it), or VB will close completly.===Conclusion=======================================================You now know how multi-threading works. You will be able to get rid of all (almost all) of your 'DoEvents' and your programs will run much faster.After a few crashes you should get the hang of it :)I wrote this tutorial for www.Axion-Network.net, but since me information is free you can distribute it anywhere as long as you leave everything unchanged. If you feel something needs to be changed or added, e-mail me.For all my texts go to Http://kickme.to/axe - another good place is http://gremlin.vectorstar.net/cgi-bin/1.cgi - but because of grem's hate for VB I decided not to even bother him with this text ;)Sence this is my second text, and I wrote them both in the same day they look very much like the same... I don't know if I want it my style or what at the time.
至于多线程Private Declare Function CreateThread Lib "kernel32" (ByVal Null1 As Long, ByVal Null2 As Long, ByVal StartAddress As Long, Parameter As Any, ByVal Null3 As Long, ThreadId As Long) As Long这个是最关键函数 不过VB的本身不是线程安全的,所以使用它的时候会有很多问题,一般用在ActiveX中比较好,使用它的办法如下 Dim Identifier As Long CreateThread 0, 0, AddressOf 函数名, 0, 0, Identifier 尽量使用没有参数的函数,会减低使用的危险性,而且这个函数得是在模块中,否则你无法用Addressof取得它的起始地址
VB中的线程太稳定了,建议使用timer来替代.
[名称] 创建多线程[数据来源] 未知[内容简介] 空[源代码内容] 'clsThreading: Class Model 'Simple class that allows you to implement multithreading in your app ' '(C) 2001 by Philipp Weidmann'API Declarations 'Creates a new thread Private Declare Function CreateThread Lib "kernel32" (ByVal lpThreadAttributes As Any, ByVal dwStackSize As Long, ByVal lpStartAddress As Long, lpParameter As Any, ByVal dwCreationFlags As Long, lpThreadID As Long) As Long 'Terminates a thread Private Declare Function TerminateThread Lib "kernel32" (ByVal hThread As Long, ByVal dwExitCode As Long) As Long 'Sets the priority of a thread Private Declare Function SetThreadPriority Lib "kernel32" (ByVal hThread As Long, ByVal nPriority As Long) As Long 'Returns the proirity of a thread Private Declare Function GetThreadPriority Lib "kernel32" (ByVal hThread As Long) As Long 'Enables a disabled Thread Private Declare Function ResumeThread Lib "kernel32" (ByVal hThread As Long) As Long 'Disables a thread Private Declare Function SuspendThread Lib "kernel32" (ByVal hThread As Long) As Long 'Returns the handle of the current thread Private Declare Function GetCurrentThread Lib "kernel32" () As Long 'Returns the ID of the current thread Private Declare Function GetCurrentThreadId Lib "kernel32" () As Long'Consts Private Const MAXLONG = &H7FFFFFFF'Thread priority consts Private Const THREAD_BASE_PRIORITY_IDLE = -15 Private Const THREAD_BASE_PRIORITY_LOWRT = 15 Private Const THREAD_BASE_PRIORITY_MAX = 2 Private Const THREAD_BASE_PRIORITY_MIN = -2 Private Const THREAD_PRIORITY_HIGHEST = THREAD_BASE_PRIORITY_MAX Private Const THREAD_PRIORITY_LOWEST = THREAD_BASE_PRIORITY_MIN Private Const THREAD_PRIORITY_ABOVE_NORMAL = (THREAD_PRIORITY_HIGHEST - 1) Private Const THREAD_PRIORITY_BELOW_NORMAL = (THREAD_PRIORITY_LOWEST + 1) Private Const THREAD_PRIORITY_ERROR_RETURN = (MAXLONG) Private Const THREAD_PRIORITY_IDLE = THREAD_BASE_PRIORITY_IDLE Private Const THREAD_PRIORITY_NORMAL = 0 Private Const THREAD_PRIORITY_TIME_CRITICAL = THREAD_BASE_PRIORITY_LOWRT'Thread creation flags Private Const CREATE_ALWAYS = 2 Private Const CREATE_NEW = 1 Private Const CREATE_NEW_CONSOLE = &H10 Private Const CREATE_NEW_PROCESS_GROUP = &H200 Private Const CREATE_NO_WINDOW = &H8000000 Private Const CREATE_PROCESS_DEBUG_EVENT = 3 Private Const CREATE_SUSPENDED = &H4 Private Const CREATE_THREAD_DEBUG_EVENT = 2'Types and Enums Public Enum ThreadPriority tpLowest = THREAD_PRIORITY_LOWEST tpBelowNormal = THREAD_PRIORITY_BELOW_NORMAL tpNormal = THREAD_PRIORITY_NORMAL tpAboveNormal = THREAD_PRIORITY_ABOVE_NORMAL tpHighest = THREAD_PRIORITY_HIGHEST End Enum'Vars Private mThreadHandle As Long Private mThreadID As Long Private mPriority As Long Private mEnabled As Boolean Private mCreated As BooleanPublic Function CreateNewThread(ByVal cFunction As Long, Optional ByVal cPriority As Long = tpNormal, Optional ByVal cEnabled As Boolean = True) 'Creates a new Thread Dim mHandle As Long Dim CreationFlags As Long Dim lpThreadID As Long
'Look if the thread has already been created If mCreated = True Then Exit Function
'Look if the thread should be enabled If cEnabled = True Then CreationFlags = 0 Else 'Create a disabled thread, can be enabled later with the ''Enabled' property CreationFlags = CREATE_SUSPENDED End If
'The CreateThread Function returns the handle of the created thread; 'if the handle is 0, it failed creating the thread mHandle = CreateThread(ByVal 0&, ByVal 0&, cFunction, ByVal 0&, CreationFlags, lpThreadID)
If mHandle = 0 Then 'Failed creating the thread 'Insert your own error handling 'Debug.Print "InitializeThread Function in clsThreading failed creating a new thread" Else mThreadHandle = mHandle mThreadID = lpThreadID mCreated = True End If End FunctionPublic Function TerminateCurrentThread() 'Terminates the current thread
'Ignore errors to prevent crashing if no thread has been created On Error Resume Next 'Terminate the thread to prevent crashing if the app is closed 'and the thread is still running (dangerous!) Call TerminateThread(mThreadHandle, ByVal 0&) mCreated = False End FunctionPublic Property Get ThreadHandle() As Long 'Returns the Handle of the current Thread ThreadHandle = mThreadHandle End PropertyPublic Property Get ThreadID() As Long 'Returns the ID of the current thread ThreadID = mThreadID End PropertyPublic Property Get Priority() As Long 'Returns a long value because the thread might have other priorities 'than our five in the enum
'Ignore errors to prevent crashing if no thread has been created On Error Resume Next Priority = GetThreadPriority(mThreadHandle) End PropertyPublic Property Let Priority(ByVal tmpValue As Long) 'Sets the Thread Priority of the actual thread mPriority = tmpValue Call SetThreadPriority(mThreadHandle, tmpValue) End PropertyPublic Property Get Enabled() As Boolean 'Returns whether the Thread is enabled or not Enabled = mEnabled End PropertyPublic Property Let Enabled(ByVal tmpValue As Boolean) 'Enables/Disables the Thread
'Ignore errors to prevent crashing if no thread has been created On Error Resume Next If tmpValue = True Then 'Enable the thread Call ResumeThread(mThreadHandle) ElseIf tmpValue = False Then 'Disable the thread Call SuspendThread(mThreadHandle) End If End PropertyPrivate Sub Class_Terminate() 'Terminate the thread to prevent crashing if the app is closed 'and the thread is still running (dangerous!) Call TerminateCurrentThread End Sub 以上代码保存于: SourceCode Explorer(源代码数据库) 复制时间: 2003-1-6 19:51:58 软件版本: 1.0.815 软件作者: Shawls 个人主页: Http://Shawls.Yeah.Net E-Mail: [email protected] QQ: 9181729
Public Declare Function SetWindowText Lib "user32" Alias "SetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String) As Longin form
private Declare Function SetWindowText Lib "user32" Alias "SetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String) As Long
Declare Function SetWindowText Lib "user32" Alias "SetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String) As Long
说明
设置窗口的标题文字或控件的内容(在vb里使用:针对vb窗体,应使用caption或text属性)
返回值
Long,非零表示成功,零表示失败。会设置GetLastError
参数表
参数 类型及说明
hwnd Long,要设置文字的窗口的句柄
lpString String,要设到hwnd窗口中的文字
Revision 1.0.0
By: AxE ([email protected])===Intro============================================================This is my second text, I don't do spell check, and I don't write a lot.
This text is also ment for someone who knows about VB.Multithreading in VB in some cases can be dangerous, and you might need to
reboot your system. Who cares though, Windows makes you do that anyway. But
still, if you mess up your computer or anything its your own fault. I'm just
providing information.===Getting started==================================================In order to multi-thread in VB you need two API calls:Private Declare Function CreateThread Lib "kernel32" (ByVal lpThreadAttributes As Any,
ByVal dwStackSize As Long, ByVal lpStartAddress As Long, lpParameter As Any,
ByVal dwCreationFlags As Long, lpThreadID As Long) As Long
Private Declare Function TerminateThread Lib "kernel32" (ByVal hThread As Long,
ByVal dwExitCode As Long) As LongCreateThread will start the thread, and TerminateThread will terminate it..
suprise suprise. Add this global also:Dim id As LongI leave all the control names their defalut names for simplicity.
Put all the code listed in this this secion in your form's general
declarations.===Setting everything up============================================Add a textbox that is multi-lined and has vertical scroll bars and two
command buttons to your form. Label one "Start" and one "Stop"Create a Function, the code should look something like this:Public Function AddText()
Do
Form1.Text1.SelText = "Adding to Text1 - "
Loop
End FunctionThis function MUST be in a moduleYou should know not to run this because if you did you would have to kill
VB and you would loose your work and have to start over again. This is
when multi-threading becomes your best friend. Of corse you will want to
use multi-threading for something else, but this is just a example ;)I know this should be a sub too, but multi-threading only works with
functions (or so I think, I don't want to "waste time" and try it out,
let me know if I'm wrong ;))===Starting a thread================================================This is what your Command1 (Start) button should be coded like:Private Sub Command1_Click()
id = CreateThread(ByVal 0&, ByVal 0&, AddressOf AddText, ByVal 0&, 0, id)
End SubWe use 'ByVal 0&' because we don't care about those, and just put a NULL value.'AddressOf AddText' will tell the api function where the function you want
to multi-thread is located. You can just use the same code and have it go to
the address of what ever functions you want to multi-thread.'id' sets the thread number, so you can use it to kill the thread when you are
done with it.===Ending a thread==================================================This is what your Command2 (Stop) button should be coded like:Private Sub Command2_Click()
Call TerminateThread(id, ByVal 0&)
End SubOn creating a thread, you held its PID in the variable id, so you know
where it is when you want to kill it.You MUST end a thread before you end your program, otherwise you will have
a loose thread running on your computer... thats not good.===Whats going on===================================================You might think this is no big deal, but I dare you to try that function
without multi-threading it first! Your program will freeze, and you wont
be able to do anything. It will just scroll text in the textbox as it runs.
You will have to kill VB to get out of it.For a experiment, add a DoEvents in the loop, and run it wihout
multi-threading. You will see that you can click on the tile bar, move it
around as you wish, and close it also. But notice how when you do anything
else the scrolling of the text will stop? You can only do one thing at a
time...Now, when you multithread the function, fun things happen :) If you scroll
the window around, you will notice that the text is still being added to
the TextBox! The program is now able to do more than one task.Like I said, it might not seem so great right now, but this is just an
example... imagine never needing to use DoEvents again, and able to do
as many tasks as your CPU can handle at one time... for most compuers now
thats a lot of tasks ;)The problem with multi-tasking is, VB still doesnt like multi-taking, so
you must compile to run your programs with multi-tasking to run correctly.
Most of the time if you run it from VB it will just not go back to the
programming part of VB (and you need to kil it), or VB will close completly.===Conclusion=======================================================You now know how multi-threading works. You will be able to get rid of all
(almost all) of your 'DoEvents' and your programs will run much faster.After a few crashes you should get the hang of it :)I wrote this tutorial for www.Axion-Network.net, but since me information is
free you can distribute it anywhere as long as you leave everything unchanged.
If you feel something needs to be changed or added, e-mail me.For all my texts go to Http://kickme.to/axe - another good place is
http://gremlin.vectorstar.net/cgi-bin/1.cgi - but because of grem's hate for
VB I decided not to even bother him with this text ;)Sence this is my second text, and I wrote them both in the same day they
look very much like the same... I don't know if I want it my style or what
at the time.
不过VB的本身不是线程安全的,所以使用它的时候会有很多问题,一般用在ActiveX中比较好,使用它的办法如下 Dim Identifier As Long
CreateThread 0, 0, AddressOf 函数名, 0, 0, Identifier
尽量使用没有参数的函数,会减低使用的危险性,而且这个函数得是在模块中,否则你无法用Addressof取得它的起始地址
'Simple class that allows you to implement multithreading in your app
'
'(C) 2001 by Philipp Weidmann'API Declarations
'Creates a new thread
Private Declare Function CreateThread Lib "kernel32" (ByVal lpThreadAttributes As Any, ByVal dwStackSize As Long, ByVal lpStartAddress As Long, lpParameter As Any, ByVal dwCreationFlags As Long, lpThreadID As Long) As Long
'Terminates a thread
Private Declare Function TerminateThread Lib "kernel32" (ByVal hThread As Long, ByVal dwExitCode As Long) As Long
'Sets the priority of a thread
Private Declare Function SetThreadPriority Lib "kernel32" (ByVal hThread As Long, ByVal nPriority As Long) As Long
'Returns the proirity of a thread
Private Declare Function GetThreadPriority Lib "kernel32" (ByVal hThread As Long) As Long
'Enables a disabled Thread
Private Declare Function ResumeThread Lib "kernel32" (ByVal hThread As Long) As Long
'Disables a thread
Private Declare Function SuspendThread Lib "kernel32" (ByVal hThread As Long) As Long
'Returns the handle of the current thread
Private Declare Function GetCurrentThread Lib "kernel32" () As Long
'Returns the ID of the current thread
Private Declare Function GetCurrentThreadId Lib "kernel32" () As Long'Consts
Private Const MAXLONG = &H7FFFFFFF'Thread priority consts
Private Const THREAD_BASE_PRIORITY_IDLE = -15
Private Const THREAD_BASE_PRIORITY_LOWRT = 15
Private Const THREAD_BASE_PRIORITY_MAX = 2
Private Const THREAD_BASE_PRIORITY_MIN = -2
Private Const THREAD_PRIORITY_HIGHEST = THREAD_BASE_PRIORITY_MAX
Private Const THREAD_PRIORITY_LOWEST = THREAD_BASE_PRIORITY_MIN
Private Const THREAD_PRIORITY_ABOVE_NORMAL = (THREAD_PRIORITY_HIGHEST - 1)
Private Const THREAD_PRIORITY_BELOW_NORMAL = (THREAD_PRIORITY_LOWEST + 1)
Private Const THREAD_PRIORITY_ERROR_RETURN = (MAXLONG)
Private Const THREAD_PRIORITY_IDLE = THREAD_BASE_PRIORITY_IDLE
Private Const THREAD_PRIORITY_NORMAL = 0
Private Const THREAD_PRIORITY_TIME_CRITICAL = THREAD_BASE_PRIORITY_LOWRT'Thread creation flags
Private Const CREATE_ALWAYS = 2
Private Const CREATE_NEW = 1
Private Const CREATE_NEW_CONSOLE = &H10
Private Const CREATE_NEW_PROCESS_GROUP = &H200
Private Const CREATE_NO_WINDOW = &H8000000
Private Const CREATE_PROCESS_DEBUG_EVENT = 3
Private Const CREATE_SUSPENDED = &H4
Private Const CREATE_THREAD_DEBUG_EVENT = 2'Types and Enums
Public Enum ThreadPriority
tpLowest = THREAD_PRIORITY_LOWEST
tpBelowNormal = THREAD_PRIORITY_BELOW_NORMAL
tpNormal = THREAD_PRIORITY_NORMAL
tpAboveNormal = THREAD_PRIORITY_ABOVE_NORMAL
tpHighest = THREAD_PRIORITY_HIGHEST
End Enum'Vars
Private mThreadHandle As Long
Private mThreadID As Long
Private mPriority As Long
Private mEnabled As Boolean
Private mCreated As BooleanPublic Function CreateNewThread(ByVal cFunction As Long, Optional ByVal cPriority As Long = tpNormal, Optional ByVal cEnabled As Boolean = True)
'Creates a new Thread
Dim mHandle As Long
Dim CreationFlags As Long
Dim lpThreadID As Long
'Look if the thread has already been created
If mCreated = True Then Exit Function
'Look if the thread should be enabled
If cEnabled = True Then
CreationFlags = 0
Else
'Create a disabled thread, can be enabled later with the
''Enabled' property
CreationFlags = CREATE_SUSPENDED
End If
'The CreateThread Function returns the handle of the created thread;
'if the handle is 0, it failed creating the thread
mHandle = CreateThread(ByVal 0&, ByVal 0&, cFunction, ByVal 0&, CreationFlags, lpThreadID)
If mHandle = 0 Then 'Failed creating the thread
'Insert your own error handling
'Debug.Print "InitializeThread Function in clsThreading failed creating a new thread"
Else
mThreadHandle = mHandle
mThreadID = lpThreadID
mCreated = True
End If
End FunctionPublic Function TerminateCurrentThread()
'Terminates the current thread
'Ignore errors to prevent crashing if no thread has been created
On Error Resume Next
'Terminate the thread to prevent crashing if the app is closed
'and the thread is still running (dangerous!)
Call TerminateThread(mThreadHandle, ByVal 0&)
mCreated = False
End FunctionPublic Property Get ThreadHandle() As Long
'Returns the Handle of the current Thread
ThreadHandle = mThreadHandle
End PropertyPublic Property Get ThreadID() As Long
'Returns the ID of the current thread
ThreadID = mThreadID
End PropertyPublic Property Get Priority() As Long
'Returns a long value because the thread might have other priorities
'than our five in the enum
'Ignore errors to prevent crashing if no thread has been created
On Error Resume Next
Priority = GetThreadPriority(mThreadHandle)
End PropertyPublic Property Let Priority(ByVal tmpValue As Long)
'Sets the Thread Priority of the actual thread
mPriority = tmpValue
Call SetThreadPriority(mThreadHandle, tmpValue)
End PropertyPublic Property Get Enabled() As Boolean
'Returns whether the Thread is enabled or not
Enabled = mEnabled
End PropertyPublic Property Let Enabled(ByVal tmpValue As Boolean)
'Enables/Disables the Thread
'Ignore errors to prevent crashing if no thread has been created
On Error Resume Next
If tmpValue = True Then
'Enable the thread
Call ResumeThread(mThreadHandle)
ElseIf tmpValue = False Then
'Disable the thread
Call SuspendThread(mThreadHandle)
End If
End PropertyPrivate Sub Class_Terminate()
'Terminate the thread to prevent crashing if the app is closed
'and the thread is still running (dangerous!)
Call TerminateCurrentThread
End Sub
以上代码保存于: SourceCode Explorer(源代码数据库)
复制时间: 2003-1-6 19:51:58
软件版本: 1.0.815
软件作者: Shawls
个人主页: Http://Shawls.Yeah.Net
E-Mail: [email protected]
QQ: 9181729
这里有VB多线程的完整例子:http://www.csdn.net/cnshare/soft/15/15089.shtm