VB命令列參數分隔, 類似C語言中的main(int argc, char* argv[])

來源:互聯網
上載者:User

標籤:

 

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[])

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.