標籤:
VB6.0為了提供命令列參數的支援,提供了Command()介面,於是通過 Command() 函數可以得到所有傳入的參數,但是很不友好的是,VB的所有參數都被合在了一起,成為了一個字串,當有多個參數時,要想使用就不那麼方便了,於是,於是就有了下面的代碼,代碼我不記得是來自哪裡了,如果你是文章的作者,請通知我一下[email protected]@
Option Explicit
Private Declare Function GetCommandLineW Lib "kernel32" () As Long
Private Declare Function lstrlenW Lib "kernel32" (ByVal lpString As Long) As Long
Private Declare Function CommandLineToArgvW Lib "shell32" (ByVal lpCmdLine As Long, pnNumArgs As Long) As Long
Private Declare Function LocalFree Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Public Function SplitCmd(ByRef Argc As Long, ByRef Argv() As String)
Dim nNumArgs As Long ‘//命令列參數個數
Dim lpszArglist As Long ‘//命令列參數數組地址
Dim lpszArg As Long ‘//命令列各參數地址
Dim nArgLength As Long ‘//命令列各參數長度
Dim szArg() As Byte ‘//命令列各參數
Dim i As Long
lpszArglist = CommandLineToArgvW(GetCommandLineW(), nNumArgs)
If lpszArglist Then
Argc = nNumArgs ‘//輸出總個數
ReDim Argv(nNumArgs - 1)
CopyMemory ByVal VarPtr(lpszArg), ByVal lpszArglist, 4 ‘//得到argv(0)的地址
For i = 0 To nNumArgs - 1
nArgLength = lstrlenW(lpszArg)
ReDim szArg(nArgLength * 2 - 1)
CopyMemory ByVal VarPtr(szArg(0)), ByVal lpszArg, nArgLength * 2
Argv(i) = CStr(szArg)
lpszArg = lpszArg + nArgLength * 2 + 2
Next
Erase szArg
Call LocalFree(lpszArglist)
End If
End Function
調用方式很簡單,入口函數 SplitCmd(ByRef Argc As Long, ByRef Argv() As String) ,第一個參數為傳入參數:參數的總個數,第二參數是參數數組,需要說明的是,這個函數的傳回值同C語言的一樣,Argc中至少有一個值,那就是程式本身的路徑,Argv(0) 也即為程式本身的路徑,下面提供一種使用方法.
Option Explicit
Private Sub Form_Load()
Dim Argc As Long, Argv() As String
Dim i As Integer, szCmd As String
Call SplitCmd(Argc, Argv())
For i = 0 To Argc - 1
szCmd = szCmd & i & vbTab & Argv(i) & vbCrLf
Next
MsgBox szCmd
End Sub
這樣,將得到類似如下的結果:
到此,一切順利.
女孩不哭(QQ:191035066)@2011-11-13 16:02
分類: VB6.0
VB命令列參數分隔, 類似C語言中的main(int argc, char* argv[])