當前位置:編程學習大全網 - 圖片素材 - VB WaitForSingleObject不假死等待進程怎麽做

VB WaitForSingleObject不假死等待進程怎麽做

WaitForSingleObject這個壹般是多線程的時候用的,用來同步線程的。

給妳壹個例子吧。

'以下在TEvent.Cls

Option Explicit

Const INFINITE = &HFFFF

Const ERROR_ALREADY_EXISTS = 183&

Const WAIT_TIMEOUT = &H102

Private Declare Function CreateEvent Lib "kernel32" Alias "CreateEventA" _(lpEventAttributes As Any, ByVal bManualReset As Long, _ByVal bInitialState As Long, ByVal lpName As String) As Long

Private Declare Function SetEvent Lib "kernel32" (ByVal hEvent As Long) As Long

Private Declare Function ResetEvent Lib "kernel32" (ByVal hEvent As Long) As Long

Private Declare Function PulseEvent Lib "kernel32" (ByVal hEvent As Long) As Long

Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, _ByVal dwMilliseconds As Long) As Long

Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Private hEvent As Long

Private m_TimeOut As Long

Public Function Create(ByVal EventName As String) As Long

If EventName = "" Then

Create = -1

Exit Function

End If

If hEvent <> 0 Then

Create = 0

Exit Function

End If

Dim i As Long

hEvent = CreateEvent(ByVal 0, 1, 0, EventName)

If i = 0 Then

Create = 1

End If

End Function

Public Sub DelEvent()

Call CloseHandle(hEvent)

hEvent = 0

End Sub

Public Sub Signal()

Call SetEvent(hEvent)

End Sub

Public Sub PulseSignal()

Call PulseEvent(hEvent)

End Sub

Public Sub UnSignal()

Call ResetEvent(hEvent)

End Sub

Public Function ChkSignaled()

If hEvent = 0 Then

ChkSignaled = -1

Exit Function

End If

Dim i As Long

i = WaitForSingleObject(hEvent, m_TimeOut)

If i = 0 Then

ChkSignaled = 1

Else

If i = WAIT_TIMEOUT Then

ChkSignaled = 0

Else

ChkSignaled = -1

End If

End If

End Function

Public Property Get TimeOut() As Long

TimeOut = m_TimeOut

End Property

Public Property Let TimeOut(ByVal vNewValue As Long)

If vNewValue < 0 Then

vNewValue = 0

End If

m_TimeOut = vNewValue

End Property

Private Sub Class_Initialize()

m_TimeOut = INFINITE

End Sub

Private Sub Class_Terminate()

Call DelEvent

End Sub

'以下在Form 需3個Command Button 壹個label

Option Explicit

Dim aa As New TEvent

Private Sub Command1_Click()

aa.Signal

End Sub

Private Sub Command2_Click()

aa.UnSignal

End Sub

Private Sub Command3_Click()

Dim i As Long

aa.TimeOut = 5000

i = aa.ChkSignaled

Label1.Caption = "等待中"

DoEvents

If i = 1 Then

Label1.Caption = "綠燈了"

Else

Label1.Caption = "Time Out了"

End If

End Sub

Private Sub Form_Load()

aa.Create ("MyEvent")

End Sub

還不清楚可以加我,壹般晚上在的。

  • 上一篇:老鼠為什麽又叫耗子?
  • 下一篇:會聲會影軟件怎麽保存視頻?保存視頻的教程?
  • copyright 2024編程學習大全網