Автор вопроса: Nevil | Web-сайт:allforuser.h10.ru | ICQ: 339041094
Снова здраствуйте!
У меня такой вопрос: как все файлы !указанного! каталога записать в ListBox, очень надо!
И еще один: как отследить находится ли юзверь в нэте или нет? если находится то выполнить действие, ну тоже самое и что и автоматическое обновление, как только пользователь входит в нэт...обновления начинаю автоматически закачиваться!
'Create a form with a command button (command1), a list box (list1)
'and four text boxes (text1, text2, text3 and text4).
'Type in the first textbox a startingpath like c:\
'and in the second textbox you put a pattern like *.* or *.txt
Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long
Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long
Private Type FILETIME
dwLowDateTime As Long
dwHighDateTime As Long
End Type
Private Type WIN32_FIND_DATA
dwFileAttributes As Long
ftCreationTime As FILETIME
ftLastAccessTime As FILETIME
ftLastWriteTime As FILETIME
nFileSizeHigh As Long
nFileSizeLow As Long
dwReserved0 As Long
dwReserved1 As Long
cFileName As String * MAX_PATH
cAlternate As String * 14
End Type
Function StripNulls(OriginalStr As String) As String
If (InStr(OriginalStr, Chr(0)) > 0) Then
OriginalStr = Left(OriginalStr, InStr(OriginalStr, Chr(0)) - 1)
End If
StripNulls = OriginalStr
End Function
Function FindFilesAPI(path As String, SearchStr As String, FileCount As Integer, DirCount As Integer)
'KPD-Team 1999
'E-Mail: KPDTeam@Allapi.net
'URL: http://www.allapi.net/
Dim FileName As String ' Walking filename variable...
Dim DirName As String ' SubDirectory Name
Dim dirNames() As String ' Buffer for directory name entries
Dim nDir As Integer ' Number of directories in this path
Dim i As Integer ' For-loop counter...
Dim hSearch As Long ' Search Handle
Dim WFD As WIN32_FIND_DATA
Dim Cont As Integer
If Right(path, 1) <> "\" Then path = path & "\"
' Search for subdirectories.
nDir = 0
ReDim dirNames(nDir)
Cont = True
hSearch = FindFirstFile(path & "*", WFD)
If hSearch <> INVALID_HANDLE_VALUE Then
Do While Cont
 irName = StripNulls(WFD.cFileName)
' Ignore the current and encompassing directories.
If (DirName <> "." And (DirName <> ".." Then
' Check for directory with bitwise comparison.
If GetFileAttributes(path & DirName) And FILE_ATTRIBUTE_DIRECTORY Then
dirNames(nDir) = DirName
 irCount = DirCount + 1
nDir = nDir + 1
ReDim Preserve dirNames(nDir)
End If
End If
Cont = FindNextFile(hSearch, WFD) 'Get next subdirectory.
Loop
Cont = FindClose(hSearch)
End If
' Walk through this directory and sum file sizes.
hSearch = FindFirstFile(path & SearchStr, WFD)
Cont = True
If hSearch <> INVALID_HANDLE_VALUE Then
While Cont
FileName = StripNulls(WFD.cFileName)
If (FileName <> "." And (FileName <> ".." Then
FindFilesAPI = FindFilesAPI + (WFD.nFileSizeHigh * MAXDWORD) + WFD.nFileSizeLow
FileCount = FileCount + 1
List1.AddItem path & FileName
End If
Cont = FindNextFile(hSearch, WFD) ' Get next file
Wend
Cont = FindClose(hSearch)
End If
' If there are sub-directories...
If nDir > 0 Then
' Recursively walk into them...
For i = 0 To nDir - 1
FindFilesAPI = FindFilesAPI + FindFilesAPI(path & dirNames(i) & "\", SearchStr, FileCount, DirCount)
Next i
End If
End Function
Sub Command1_Click()
Dim SearchPath As String, FindStr As String
Dim FileSize As Long
Dim NumFiles As Integer, NumDirs As Integer
Screen.MousePointer = vbHourglass
List1.Clear
SearchPath = Text1.Text
FindStr = Text2.Text
FileSize = FindFilesAPI(SearchPath, FindStr, NumFiles, NumDirs)
Text3.Text = NumFiles & " Files found in " & NumDirs + 1 & " Directories"
Text4.Text = "Size of files found under " & SearchPath & " = " & Format(FileSize, "#,###,###,##0" & " Bytes"
Screen.MousePointer = vbDefault
End Sub
1. Да не проще ли создать динамически FileListBox и слить оттуда?
2.
API Guide форева!
Private Declare Function InetIsOffline Lib "url.dll" (ByVal dwFlags As Long) As Long
Private Sub Form_Load()
'KPD-Team 2001
'URL: http://www.allapi.net/
'E-Mail: KPDTeam@Allapi.net
'InetIsOffline returns 0 if you're connected
MsgBox "Are you connected to the internet? " + CStr(CBool(Not (InetIsOffline(0)))), vbInformation
End Sub
тю, так зачем, вроде и FileListBox такой же как и ListBox, только пару свойство которые указывают с какого каталога отобразить, зачем его ещё в ListBox?
2. Очень много вопросов по этой теме было, жаль фрум грохнулся... а то бы мы тебя на поиск тыкнули ну а так:
На форме:
Option1(0) Option1(1) Option1(2)
Command1
Text1
И код:
'Working with registry declarations and constants
Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As Long
Private Declare Function RegOpenKey Lib "advapi32.dll" Alias "RegOpenKeyA" (ByVal hKey As Long, ByVal lpSubKey As String, phkResult As Long) As Long
Private Declare Function RegQueryValueEx Lib "advapi32.dll" Alias "RegQueryValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal lpReserved As Long, lpType As Long, lpData As Any, lpcbData As Long) As Long
Private Const ERROR_SUCCESS = 0&
Private Const APINULL = 0&
Private Const HKEY_LOCAL_MACHINE = &H80000002
'Working with wininet.dll declarations and constants
Private Declare Function InternetGetConnectedStateEx Lib "wininet.dll" Alias "InternetGetConnectedStateExA" (ByRef lpdwFlags As Long, ByVal lpszConnectionName As String, ByVal dwNameLen As Long, ByVal dwReserved As Long) As Long 'Private Declare Function InternetGetConnectedState Lib "wininet.dll" (ByRef lpdwFlags As Long, ByVal dwReserved As Long) As Long 'this function used with IE4
'Private Declare Function InternetGetConnectedState Lib "wininet.dll" (ByRef lpdwFlags As Long, ByVal dwReserved As Long) As Long 'this function used with IE4
Private Const INTERNET_CONNECTION_MODEM = &H1&
Private Const INTERNET_CONNECTION_LAN = &H2&
Private Const INTERNET_CONNECTION_PROXY = &H4&
Private Const INTERNET_RAS_INSTALLED = &H10&
Private Const INTERNET_CONNECTION_OFFLINE = &H20&
Private Const INTERNET_CONNECTION_CONFIGURED = &H40&
'Declares for direct ping
Private Declare Function InternetOpen Lib "wininet.dll" Alias "InternetOpenA" (ByVal lpszAgent As String, ByVal dwAccessType As Long, ByVal lpszProxyName As String, ByVal lpszProxyBypass As String, ByVal dwFlags As Long) As Long
Private Declare Function InternetOpenUrl Lib "wininet.dll" Alias "InternetOpenUrlA" (ByVal hInet As Long, ByVal lpszUrl As String, ByVal lpszHeaders As String, ByVal dwHeadersLength As Long, ByVal dwFlags As Long, ByVal dwContext As Long) As Long
Private Declare Function InternetCloseHandle Lib "wininet.dll" (ByVal hInet As Long) As Long
Private Const INTERNET_OPEN_TYPE_PRECONFIG = 0
Private Const INTERNET_FLAG_RELOAD = &H80000000
Private Const INTERNET_FLAG_KEEP_CONNECTION = &H400000
Private Const INTERNET_FLAG_NO_CACHE_WRITE = &H4000000
Dim checkType As Integer
Dim remMsg(2) As String
Private Sub Command1_Click()
Select Case checkType
Case 0
CheckConnection1
Case 1
CheckConnection2
Case 2
CheckConnection3
Case Else
End Select
End Sub
Private Sub Form_Load()
remMsg(0) = "This is the easiest way to check connection. Checking registry value of System\CurrentControlSet\Services\RemoteAccess from HKEY_LOCAL_MACHINE. Using RegOpenKey function from advapi32.dll. Unfortunately, checking is ONLY for MODEM connection. If you are connecting to Internet via Local Area Network (LAN), this method return False even if you are connected"
remMsg(1) = "This method use InternetGetConnectedStateEx function from wininet.dll. In addition, you can receive some more information about connection - Type of connection (LAN/Modem), Using of Proxy, RAS installing, OnLine/OffLine. It's work fine, but there is one problem. If your computer is in Local Area Network but you are connecting to Internet via modem, this method always returns True, in case you are connecting to Internet or not"
remMsg(2) = "This method use direct ping to some Internet address (URL) and checking for connection errors. Now it use http:/www.yahoo.com. It's not so quickly, as previous two, but this method is the most reliable"
Option1(0).Value = True
Option1(0).Caption = "Using registry"
Option1(1).Caption = "Using InternetGetConnectedStateEx"
Option1(2).Caption = "Using direct ping to www.yahoo.com"
Text1 = remMsg(0)
End Sub
Private Sub Option1_Click(Index As Integer)
checkType = Index
Text1 = remMsg(Index)
End Sub
'This part of code is from http://www.VB-world.net with my corrections
Private Sub CheckConnection1()
Dim ReturnCode As Long
Dim hKey As Long
Dim lpSubKey As String
Dim phkResult As Long
Dim lpValueName As String
Dim lpReserved As Long
Dim lpType As Long
Dim lpData As Long
Dim lpcbData As Long
lpSubKey = "System\CurrentControlSet\Services\RemoteAccess" & Chr$(0)
ReturnCode = RegOpenKey(HKEY_LOCAL_MACHINE, lpSubKey, phkResult)
If ReturnCode = ERROR_SUCCESS Then
hKey = phkResult
lpValueName = "Remote Connection"
lpReserved = APINULL
lpType = APINULL
lpData = APINULL
lpcbData = APINULL
ReturnCode = RegQueryValueEx(hKey, lpValueName, lpReserved, lpType, ByVal lpData, lpcbData)
lpcbData = Len(lpData)
ReturnCode = RegQueryValueEx(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData)
If ReturnCode = ERROR_SUCCESS Then
If lpData = 0 Then
MsgBox "Your computer is not connected to Internet via modem", vbInformation, "Checing connection"
Else
MsgBox "Your computer is connected to Internet via modem", vbInformation, "Checing connection"
End If
Else
MsgBox "Your computer is not connected to Internet via modem, but it can be connected via LAN", vbInformation, "Checing connection"
End If
End If
RegCloseKey (hKey)
End Sub
Private Sub CheckConnection2(Optional ByRef ConnectionInfo As Long, Optional ByRef sConnectionName As String)
Dim dwFlags As Long
Dim sNameBuf As String, msg As String
Dim lPos As Long
sNameBuf = String$(513, 0)
If InternetGetConnectedStateEx(dwFlags, sNameBuf, 512, 0& Then
lPos = InStr(sNameBuf, vbNullChar)
If lPos > 0 Then
sConnectionName = Left$(sNameBuf, lPos - 1)
Else
sConnectionName = ""
End If
msg = "Your computer is connected to Internet" & vbCrLf & "Connection Name: " & sConnectionName
If (dwFlags And INTERNET_CONNECTION_LAN) Then
msg = msg & vbCrLf & "Connection use LAN"
ElseIf lFlags And INTERNET_CONNECTION_MODEM Then
msg = msg & vbCrLf & "Connection use modem"
End If
If lFlags And INTERNET_CONNECTION_PROXY Then msg = msg & vbCrLf & "Connection use Proxy"
If lFlags And INTERNET_RAS_INSTALLED Then
msg = msg & vbCrLf & "RAS INSTALLED"
Else
msg = msg & vbCrLf & "RAS NOT INSTALLED"
End If
If lFlags And INTERNET_CONNECTION_OFFLINE Then
msg = msg & vbCrLf & "You are OFFLINE"
Else
msg = msg & vbCrLf & "You are ONLINE"
End If
If lFlags And INTERNET_CONNECTION_CONFIGURED Then
msg = msg & vbCrLf & "Your connection is Configured"
Else
msg = msg & vbCrLf & "Your connection is not Configured"
End If
Else
msg = "Your computer is NOT connected to Internet"
End If
MsgBox msg, vbInformation, "Checking connection"
End Sub
Private Sub CheckConnection3()
 im sTmp As String
 im hInet As Long
 im hUrl As Long
 im Flags As Long
 im url As Variant
hInet = InternetOpen(App.Title, INTERNET_OPEN_TYPE_PRECONFIG, vbNullString, vbNullString, 0&
sTmp = Me.Caption
Me.Caption = "Checking connection with www.yahoo.com..."
If hInet Then
Flags = INTERNET_FLAG_KEEP_CONNECTION Or INTERNET_FLAG_NO_CACHE_WRITE Or INTERNET_FLAG_RELOAD
hUrl = InternetOpenUrl(hInet, "http://www.yahoo.com", vbNullString, 0, Flags, 0)
If hUrl Then
MsgBox "Your computer is connected to Internet", vbInformation, "Checing connection"
Call InternetCloseHandle(hUrl)
Else
MsgBox "Your computer is not connected to Internet", vbInformation, "Checing connection"
End If
End If
Call InternetCloseHandle(hInet)
Me.Caption = sTmp
End Sub
мля, кода понадавали))) вроде немного просил...
HACKER, у меня такой вопрос: как загрузить в файллистбокс файлы определенного каталога и как их от туда потом построчно считывать?
Ну тогда до кучи ещё один способ, который мало известен:
Private Declare Function DlgDirList Lib "user32.dll" Alias "lgDirListA" ( _
ByVal hDlg As Long, _
ByVal lpPathSpec As String, _
ByVal nIDListBox As Long, _
ByVal nIDStaticPath As Long, _
ByVal wFileType As Long) As Long
Private Declare Function GetDlgCtrlID Lib "user32.dll" (ByVal hwnd As Long) As Long
Private Sub Form_Load()
Dim ID As Long
ID = GetDlgCtrlID(ByVal List1.hwnd)
 lgDirList Me.hwnd, ByVal "C:\Windows\System32", ByVal ID, ByVal 0, ByVal 0
End Sub
2VladeD, че тут извиняться, если ты не заметил, то у этого кода даже нет форматирования, т.е. почти все написано нижним регистром.. это может означать лишь одно - я этот код не проверял а писал прямо от болды тут в форуме... Т.ч. разумеется что возможно он в некоторых местах и работает не так как надо
а вот на счет vba - должен работать 100%... т.ч. уж извини VladeD
Это в XP так у меня работает код без vba
Так что еще раз извини (слово без кавычек, т.е. в прчмом смысле). Дело в том, что "чем дальше в лес тем больше дров" :)
Я находил коды для VB6, которые по разному работают в Win98 и XP ??? При чем, на одной и той же машине Win98 и Win Xp и установленным VB6 из одного и того же Инстальника CD в Win 98 и XP !!!
А установочный комплект программы VB6 на XP не устанавливается на Win 2000!?
Cresta
Ваш код фономенальный!
За один проход кода весь список файлов папки в List сразу.
Я еще такого не встречал!
Очень интересный код!!!!
Спасибо. Кто заинтересуется, не пожалеет. Думаю в практике очень пригодится.