核心方法:`App.Path`属性
`App.Path`返回应用程序的启动路径,其返回值格式与应用程序位置有关:- 若程序在根目录如`C:`,返回带反斜杠的路径例:`C:`;
- 若程序在子目录如`C:MyApp`,返回不带反斜杠的路径例:`C:MyApp`。
代码示例
```vb ' 直接获取当前路径并输出 MsgBox "当前路径:" & App.Path' 拼接路径时,处理反斜杠问题避免重复或缺失 Dim fullPath As String If Right(App.Path, 1) = "" Then ' 判断路径末尾是否有反斜杠 fullPath = App.Path & "data.ini" ' 根目录下直接拼接 Else fullPath = App.Path & "data.ini" ' 子目录下添加反斜杠 End If MsgBox "整文件路径:" & fullPath ```
二、获取系统路径 系统路径包括Windows目录如`C:Windows`、系统目录如`C:WindowsSystem32`等,需通过Windows API函数获取。VB6中需先声明API,再调用函数实现。1. 获取系统目录System32
`GetSystemDirectory`函数用于获取系统目录路径32位系统为`System32`,64位系统根据程序位数可能返回`SysWOW64`。声明与使用
```vb ' 声明API函数需放在模块或窗体通用声明区 Private Declare Function GetSystemDirectory Lib "kernel32" Alias "GetSystemDirectoryA" _ (ByVal lpBuffer As String, ByVal nSize As Long) As Long' 获取系统目录 Dim sysDir As String, bufferSize As Long bufferSize = 255 ' 缓冲区大小足够存储路径 sysDir = String(bufferSize, 0) ' 初始化缓冲区 GetSystemDirectory sysDir, bufferSize ' 调用API sysDir = Left(sysDir, InStr(sysDir, Chr(0)) - 1) ' 截取有效字符串 MsgBox "系统目录:" & sysDir ' 输出结果例:C:WindowsSystem32 ```
2. 获取Windows目录
`GetWindowsDirectory`函数用于获取Windows系统目录如`C:Windows`。声明与使用
```vb ' 声明API函数需放在模块或窗体通用声明区 Private Declare Function GetWindowsDirectory Lib "kernel32" Alias "GetWindowsDirectoryA" _ (ByVal lpBuffer As String, ByVal nSize As Long) As Long' 获取Windows目录 Dim winDir As String, bufferSize As Long bufferSize = 255 winDir = String(bufferSize, 0) GetWindowsDirectory winDir, bufferSize winDir = Left(winDir, InStr(winDir, Chr(0)) - 1) MsgBox "Windows目录:" & winDir ' 输出结果例:C:Windows ```
- 当前路径:直接使用`App.Path`属性,意根据路径末尾是否带反斜杠处理拼接逻辑;
- 系统路径:通过`GetSystemDirectory`系统目录和`GetWindowsDirectory`Windows目录API函数,需先声明函数、初始化缓冲区,再截取有效路径。 以上方法可满足VB6中对路径获取的基本需求,代码简洁且兼容性良好。
