[VBA ] 請問VBA API相關問題...

作者: jacky33 (VBA API)   2015-03-02 00:12:09
小弟剛學VBA,有些問題想請高手指教,感謝。
程式碼如下(http://www.programmer-club.com.tw/ShowSameTitleN/vb/28660.html):
Private Declare Function OpenProcess Lib "kernel32" _
(ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, _
ByVal dwProcessId 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 Declare Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, lpExitCode As Long) As Long
Private Declare Function TerminateProcess Lib "kernel32" _
(ByVal hProcess As Long, ByVal uExitCode As Long) As Long
Private Declare Function GetForegroundWindow Lib "user32" () As Long
Private Declare Function IsWindow Lib "user32" _
(ByVal hwnd As Long) As Long
Const PROCESS_QUERY_INFORMATION = &H400
Const SYNCHRONIZE = &H100000
Const STILL_ALIVE = &H103
Const INFINITE = &HFFFF
Private ExitCode As Long
Private hProcess As Long
Private isDone As Long
Private Sub Command1_Click()
Dim pid As Long
pid = Shell("C:\Project1.exe", vbNormalFocus)
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION + SYNCHRONIZE, 0, pid)
isDone = False
Do
Call GetExitCodeProcess(hProcess, ExitCode)
DoEvents
Loop While ExitCode = STILL_ALIVE
Call CloseHandle(hProcess)
isDone = True
Sheet1.Cells(1, 1) = "done"
End Sub
Q1:程式內的isDone是什麼用途??為何一開始宣告它(Private isDone As Long)然後
在之後又isDone = False 和 isDone = True? 用意為何?
Q2:GetExitCodeProcess指的是中止上面執行中(或是執行完)的程式("C:\Project1.exe")嗎??
那定義ExitCode = STILL_ALIVE是什麼意思?為何不是STILL_ACTIVE
(https://msdn.microsoft.com/en-us/library/windows/desktop/ms683189(v=vs.85).aspx?
Q3:DoEvents是暫停執行,以便讓作業系統可以處理其它的事件。加了這個是為了可以執行
下面的程式Sheet1.Cells(1,1) = "done"嗎??那為何不是加在 Call CloseHandle (hProcess)
之下??
Q4:CloseHandle指的是Closes an open object handle.是不是一定都要加?不加會怎麼樣?
感謝~
作者: MOONRAKER (㊣牛鶴鰻毛人)   2015-03-02 02:40:00
你不是剛學 為什麼要看這種變態的code。
作者: jacky33 (VBA API)   2015-03-02 09:13:00
工作需要
作者: tsongs (......)   2015-03-02 14:37:00
推變態的code VBA很熟API不懂正常 VB一般不會用到這些我用api一般都是把變數換成我定義的就完工這CASE你有3個地方要改成你的定義1. Private Sub Command1_Click() 改成你的執行模式2. pid = Shell("C:\Project1.exe", vbNormalFocus)改執行檔案路徑與程式名稱3. Sheet1.Cells(1, 1) = "done" 這行可以改成呼叫你後續我在使用API時會習慣建一個模組叫API 然後COPY過去不過只COPY到1.以前 1.以後是要引用到自己寫的程序當中第一次用API 重點在怎用他
作者: wenyonba (射後不理很XX啊!!!!)   2015-03-02 21:44:00
這段程式應該是啟動project1.exe,並等他跑完,然後在Cell裡顯示已跑完吧??老實說我看不出isDone有啥用途DoEvents並不能說是"暫停",而是讓程式去處理其他的訊息因為沒有看到其他的Code無法知道isDone有何用處,不過宣告成全域或模組級,可能是當控制權由DoEvents轉移到其他地方時,那個副程式可以藉由isDone知道project1.exe跑完了沒至於為啥是STILL_ALIVE不是STILL_ACTIVE??因為如果是C,直接include正確的header就可以得到STILL_ACTIVE=0x103但是這是VBA,常數你要自己宣告好,所以名稱也由你自己定,跟C的header裡不一樣名字也沒差我回答的好像好亂啊XD
作者: johnpage (johnpage)   2015-03-02 22:19:00
Q1:isDone=確定Q2: STILL_ALIVE=仍然活著Q3:執行do loop時,沒有加 DoEvents程式會顯示無回應Q4:hook
作者: jacky33 (VBA API)   2015-03-03 00:14:00
感謝~

Links booklink

Contact Us: admin [ a t ] ucptt.com