VB命令行参数分隔, 类似C语言中的main(int argc, char* argv[])

VB6.0为了提供命令行参数的支持,提供了Command()接口,于是通过 Command() 函数可以得到所有传入的参数,但是很不友好的是,VB的所有参数都被合在了一起,成为了一个字符串,当有多个参数时,要想使用就不那么方便了,于是,于是就有了下面的代码,代码我不记得是来自哪里了,如果你是文章的作者,请通知我一下.@@

VB命令行参数分隔, 类似C语言中的main(int argc, char* argv[])
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
VB命令行参数分隔, 类似C语言中的main(int argc, char* argv[])

  调用方式很简单,入口函数 SplitCmd(ByRef Argc As Long, ByRef Argv() As String) ,第一个参数为传入参数:参数的总个数,第二参数是参数数组,需要说明的是,这个函数的返回值同C语言的一样,Argc中至少有一个值,那就是程序本身的路径,Argv(0) 也即为程序本身的路径,下面提供一种使用方法.

VB命令行参数分隔, 类似C语言中的main(int argc, char* argv[])
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
VB命令行参数分隔, 类似C语言中的main(int argc, char* argv[])

这样,将得到类似如下的结果:

VB命令行参数分隔, 类似C语言中的main(int argc, char* argv[])

到此,一切顺利.
女孩不哭(QQ:191035066)@2011-11-13 16:02

 
分类: VB6.0
 
 
 
 
 
 
 
 
 
上一篇:如何成为一位优秀的创业CEO


下一篇:MongoDB 备份(mongodump)恢复(mongorerstore) 导出 (Mongoexport) 导入( Mongoimport)