|
建立拨号联接
Public Const RAS_MaxEntryName = 256
Private Type RASENTRYNAME
dwSize As Long
szEntryName(RAS_MaxEntryName) As Byte
End Type
c 中 Char aa[16] 代表长度是16,可放 15个byte所以对应於vb便是 aa(15) as Byte
如此才是长度16 ( 0--15)。故VB的宣告中不能再用szEntryName(RAS_MaxEntryName+1)
但是Lenb(RASENTRYNAME)的长度却是 261 (4+257),的确,这是vb的问题,而c 的SizeOf
传回的是4的倍数(32位元嘛)故值为264,所以我们计算某个Structure的长度时,要再多一
些运算。
以下的Fuction只适用於32位元的win95/ NT,
'以下在Form中
Private hConn as Long
Private Sub Command1_Click()
hConn = Dialup("我的连线", "user", "passwd")
if hConn = 0 Then
Debug.Print "连线失败"
end if
End Sub
Private Sub Command2_Click()
Call HangUp(hConn)
End Sub
'以下在.bas中
Option Explicit
Public Const RAS_MaxEntryName = 256
Public Const RAS_MaxDeviceName = 128
Public Const RAS_MaxDeviceType = 16
Public Const RAS_MaxPhoneNumber = 128
Public Const RAS_MaxCallbackNumber = 128
Public Const UNLEN = 256
Public Const PWLEN = 256
Public Const DNLEN = 15
Public Const ERROR_INVALID_HANDLE = 6
Type RASDIALPARAMS
dwSize As Long '1052
szEntryName(RAS_MaxEntryName) As Byte
szPhoneNumber(RAS_MaxPhoneNumber) As Byte
szCallbackNumber(RAS_MaxCallbackNumber) As Byte
szUserName(UNLEN) As Byte
szPassword(PWLEN) As Byte
szDomain(DNLEN) As Byte
End Type
Type RASCONNSTATUS
dwSize As Long '144
RasConnState As Long
dwError As Long
szDeviceType(RAS_MaxDeviceType) As Byte
szDeviceName(RAS_MaxDeviceName) As Byte
End Type
Declare Function RasGetErrorString Lib "rasapi32" _
Alias "RasGetErrorStringA" (ByVal ErrValue As Long, ByVal lpErrStr
As String, _
ByVal cSize As Long) As Long
Declare Function RasDial Lib "rasapi32" _
Alias "RasDialA" (DialExt As Long, ByVal lpPhoneBook As String,
_
RasDialParam As RASDIALPARAMS, ByVal NotifyType As Long, _
ByVal Notifter As Long, hRasConn As Long) As Long
Declare Function RasHangUp Lib "rasapi32" Alias _
"RasHangUpA" (ByVal hRasConn As Long) As Long
Declare Function RasGetConnectStatus Lib "rasapi32" Alias _
"RasGetConnectStatusA" (ByVal hRasConn As Long, _
lprasconnstatus As RASCONNSTATUS) As Long
Declare Function RasGetEntryDialParams Lib "rasapi32" _
Alias "RasGetEntryDialParamsA" (ByVal lpszPhonebook As String,
_
lpRasDialParams As RASDIALPARAMS, _
lpfPassword As Byte) As Long
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
'自动拨接(Win95 4, 5 个参数不传,或为vbNullString)
Public Function DialUp(ByVal EntryName As String, ByVal UserN As String,
_
ByVal Pwd As String, Optional ByVal PhoneBook As String, Optional sDomain
As String) As Long
Dim RasDialPara As RASDIALPARAMS
Dim bya() As Byte, di As Long
Dim len5 As Long, i As Long
Dim hRasConn As Long
len5 = LenB(RasDialPara)
i = (4 - (len5 Mod 4)) Mod 4
RasDialPara.dwSize = len5 + i '1052
bya = StrConv(EntryName, vbFromUnicode) + ChrB(0)
Call CopyByte(RasDialPara.szEntryName, bya)
bya = StrConv(UserN, vbFromUnicode) + ChrB(0)
Call CopyByte(RasDialPara.szUserName, bya)
bya = StrConv(Pwd, vbFromUnicode) + ChrB(0)
Call CopyByte(RasDialPara.szPassword, bya)
bya = StrConv(sDomain, vbFromUnicode) + ChrB(0)
Call CopyByte(RasDialPara.szDomain, bya)
'若使用以下CallBack function的方式,则RasDial()不等连线成功或失败便结束。
di = RasDial(0, PhoneBook, RasDialPara, 0, AddressOf RasDialFunc, hRasConn)
'若第二、叁个参数都是0则,RasDial会等连线成功或失败後才执行下一行指令
'di = RasDial(0, PhoneBook, RasDialPara, 0, 0, hRasConn)
If di = 0 Then
DialUp = hRasConn
Else
DialUp = 0
Dim str5 As String
str5 = String(255, Chr(0))
Call RasGetErrorString(di, str5, 256)
MsgBox Left(str5, InStr(1, str5, Chr(0)) - 1), vbCritical
Call HangUp(hRasConn)
End If
End Function
Public Sub RasDialFunc(ByVal unMsg As Long, _
ByVal ConnState As Long, _
ByVal dwError As Long)
If ConnState = &H2000 Then
' Connect Complete
End If
'取消拨接
Public Function HangUp(ByVal hconn As Long) As Boolean
Dim st As Long, len5 As Long
Dim i As Long, ConStatus As RASCONNSTATUS
st = RasHangUp(hconn)
len5 = LenB(ConStatus)
i = (4 - (len5 Mod 4)) Mod 4
ConStatus.dwSize = len5 + i
Do While True
Call Sleep(0)
i = RasGetConnectStatus(hconn, ConStatus)
If i = ERROR_INVALID_HANDLE Then
Exit Do
End If
Loop
If st = 0 Then
HangUp = True
Else
HangUp = False
End If
End Function
Private Sub CopyByte(dest() As Byte, sour() As Byte)
Dim sourL As Long, sourU As Long
Dim destL As Long, destU As Long, i As Long, j As Long
sourL = LBound(sour)
sourU = UBound(sour)
destL = LBound(dest)
destU = UBound(dest)
j = 0
For i = sourL To sourU
dest(destL + j) = sour(i)
j = j + 1
If j >= (destU - destL) + 1 Then
Exit For
End If
Next i
End Sub
返回
WinSock断开导致客户端问题
Client断开连接后再与Server连接就连接不上,必须退出应用重新进入才能连
接, 解决是不要在 Client 端使用 Close 方法, 而在服务端使用。
服务端的数据接受过程:
Sub Server_DataArrival(ByVal bytesTotal as Long)
Dim vbStr as String
Server.GetData DataReceived, vbStr
if Cstr(DataReceived)= "QUIT" then
server.close
server.LocalPort = 1111
server.Listen
end if
。。。。。
End Sub
客户端关闭时:
Client.SendData "QUIT"
返回
用 WinSock 控件下载文件
1 增加一个 Winsock 控件, 名称为 Winsock1。
2 建立连接:
Winsock1.RemoteHost = "nease.com"
Winsock1.RemotePort = 80
Winsock1.Connect
3 在Winsock1.Connect 事件中加入:
Dim strCommand as String
Dim strWebPage as String
strWebPage = "http://www.nease.com/~kenj/index.html"
strCommand = "GET " + strWebPage + " HTTP/1.0" + vbCrLf
strCommand = strCommand + "Accept: */*" + vbCrLf
strCommand = strCommand + "Accept: text/html" + vbCrLf
strCommand = strCommand + vbCrLf
Winsock1.SendData strCommand
4 Winsock 开始下载, 在收到数据时, 发生DataArrival 事件。
Dim webData As String
Winsock1.GetData webData, vbString
TxtWebPage.Text = TxtWebPage.Text + webData
返回
在桌面上建立 Internet 快捷键
以下的代码可以在桌面上建立一个 Internet 快捷键。
Dim StrURLFile As String
Dim StrURLTarget As String
Dim FileNum As Integer
StrURLFile = "C:\Windows\Desktop\VB 加油站.url" '桌面目录和标题
StrURLTarget = "http://vbtt.yeah.net" '地址
FileNum = FreeFile
'Write the Internet Shortcut file
Open StrURLFile For Output As FileNum
Print #FileNum, "[InternetShortcut]"
Print #FileNum, "URL=" & StrURLTarget
Close FileNum
返回
判断是否已经建立 Dial Up 连接
通过读取注册表, 可以知道该信息。
声明:
Public Const ERROR_SUCCESS = 0&
Public Const APINULL = 0&Public
Const HKEY_LOCAL_MACHINE = &H80000002
Public ReturnCode As Long
Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey
As Long) As Long
Declare Function RegOpenKey Lib "advapi32.dll" Alias "RegOpenKeyA"
(ByVal hKey As Long, ByVal lpSubKey As String, phkResult As Long) As Long
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
函数:
Public Function ActiveConnection() As Boolean
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
ActiveConnection = False
lpSubKey = "System\CurrentControlSet\Services\RemoteAccess"
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
ActiveConnection = False
Else
ActiveConnection = True
End If
End If
RegCloseKey (hKey)
End If
End Function
返回
断开与 Internet 的连接
声明:
Public Const RAS_MAXENTRYNAME As Integer = 256
Public Const RAS_MAXDEVICETYPE As Integer = 16
Public Const RAS_MAXDEVICENAME As Integer = 128
Public Const RAS_RASCONNSIZE As Integer = 412
Public Type RasEntryName
dwSize As Long
szEntryName(RAS_MAXENTRYNAME) As Byte
End Type
Public Type RasConn
dwSize As Long
hRasConn As Long
szEntryName(RAS_MAXENTRYNAME) As Byte
szDeviceType(RAS_MAXDEVICETYPE) As Byte
szDeviceName(RAS_MAXDEVICENAME) As Byte
End Type
Public Declare Function RasEnumConnections Lib _
"rasapi32.dll" Alias "RasEnumConnectionsA" (lpRasConn
As _
Any, lpcb As Long, lpcConnections As Long) As Long
Public Declare Function RasHangUp Lib "rasapi32.dll" Alias _
"RasHangUpA" (ByVal hRasConn As Long) As Long
Public gstrISPName As String
Public ReturnCode As Long
函数:
Public Sub HangUp()
Dim i As Long
Dim lpRasConn(255) As RasConn
Dim lpcb As Long
Dim lpcConnections As Long
Dim hRasConn As Long
lpRasConn(0).dwSize = RAS_RASCONNSIZE
lpcb = RAS_MAXENTRYNAME * lpRasConn(0).dwSize
lpcConnections = 0
ReturnCode = RasEnumConnections(lpRasConn(0), lpcb, _
lpcConnections)
If ReturnCode = ERROR_SUCCESS Then
For i = 0 To lpcConnections - 1
If Trim(ByteToString(lpRasConn(i).szEntryName)) _
= Trim(gstrISPName) Then
hRasConn = lpRasConn(i).hRasConn
ReturnCode = RasHangUp(ByVal hRasConn)
End If
Next i
End If
End Sub
Public Function ByteToString(bytString() As Byte) As String
Dim i As Integer
ByteToString = ""
i = 0
While bytString(i) = 0&
ByteToString = ByteToString & Chr(bytString(i))
i = i + 1
Wend
End Function
返回
在程序中打开 Internet 拨号连接窗口
Private Sub StartConnection()
Dim X
X = Shell("rundll32.exe rnaui.dll,RnaDial " & "_连接的名称_",
1)
DoEvents
SendKeys "{enter}", True
DoEvents
End Sub
返回
打开浏览器并进入指定网址
声明:
Private Declare Function ShellExecute Lib "shell32.dll" Alias
"ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String,
ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory
As String, ByVal nShowCmd As Long) As Long
例子:
Dim ret&
ret& = ShellExecute(Me.hwnd, "Open", "http://vbonline.yes8.com",
"", App.Path, 1)
End Sub
也可以直接发送 Mail,只要把以上的 http 地址换为 "mailto:vbcode@21cn.com"
返回
在应用中集成浏览器
从 MS IE 3.0 开始就包括了一个名为 "WebBrowser" 的 ActiveX 控件。利用该控件,你可以开发强大的基于浏览器的应用。下面讨论如何进行集成。
1. 在 工程 菜单中, 选择 部件 。
2. 选择 Microsoft Internet Controls 。
3. 增加一个 WebBrowser 控件。
4. 使用以下的代码可连接到 VB 开发者:
WebBrowser1.Navigate "http://vbonline.yes8.com"
返回
得到用户的IP地址
最快的方法是读取 Winsock 控件的 "LocalIP" 属性。
返回
电话拨号
利用 API 可以直接拨号。声明:
Private Declare Function tapiRequestMakeCall Lib "TAPI32.DLL"
(ByVal DestAddr$, ByVal AppName As String, ByVal CalledParty As String,
ByVal Comment As String) As Long
例子:
Public Sub CallPhone(Number As String, Name As String)
Dim lRes As Long
If (Trim(Number) = "") Then
Exit Sub
End If
If (MsgBox("About to call " & Trim(Name) & " at
phone number " & Trim(Number) & vbCrLf & "Do it?",
vbYesNo, App.Title) = vbYes) Then
lRes = tapiRequestMakeCall(Trim(Number), App.Title, Trim(Name), "")
Debug.Print Now; " CallPhone -> tapiRequestMakeCall Result code
= "; lRes
End If
End Sub
还有一种方法是:
PhoneNumber$ = "(123)456-7890"
Open "COM2:" For Output As #1 'or COM1
Print #1, "ATDT" & PhoneNumber$ & Chr$(13)
Close #1
当然,该方法只适合小型的应用。
返回
利用TAPI进行电话拨号
'Phone Dialer in VB
'make a new project; 2 textboxen (index 0 & 1); 2 labels (index 0
& 1)
'1 command button
'Insert the next code in the right place (use Insert/File)
'Press F5
------------- code -------------------
Option Explicit
Private Declare Function tapiRequestMakeCall& Lib "TAPI32.DLL"
(ByVal DestAdress$, ByVal AppName$, ByVal CalledParty$, ByVal Comment$)
Private Sub ChooseNumber(strNumber As String, strAppName As String, strName
As String)
Dim lngResult As Long
Dim strBuffer As String
lngResult = tapiRequestMakeCall&(strNumber, strAppName, strName, "")
If lngResult <> 0 Then 'error
strBuffer = "Error connecting to number: "
Select Case lngResult
Case -2&
strBuffer = strBuffer & " 'PhoneDailer not installed?"
Case -3&
strBuffer = strBuffer & "Error : " & CStr(lngResult)
& "."
End Select
MsgBox strBuffer
End If
End Sub
Private Sub Command1_Click()
Call ChooseNumber(Text1(0).Text, "PhoneDialer", Text1(1).Text)
End Sub
Private Sub Form_Load()
Text1(0).Text = ""
Text1(1).Text = ""
End Sub
Private Sub Form_Unload(Cancel As Integer)
End
End Sub
返回
通过WnetEnumResource函数获得网络资源
Create a new project and add the following code to the form:
Option Explicit
Private Const GMEM_FIXED = &H0
Private Const GMEM_ZEROINIT = &H40
Private Const GPTR = (GMEM_FIXED Or GMEM_ZEROINIT)
Private Declare Function GlobalAlloc Lib "KERNEL32" ( _
ByVal wFlags As Long, ByVal dwBytes As Long) As Long
Private Declare Function GlobalFree Lib "KERNEL32" ( _
ByVal hMem As Long) As Long
Private Declare Sub CopyMemory Lib "KERNEL32" Alias "RtlMoveMemory"
_
(hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long)
Private Declare Function CopyPointer2String Lib "KERNEL32" _
Alias "lstrcpyA" ( _
ByVal NewString As String, ByVal OldString As Long) As Long
Private Sub Form_click()
Dim hEnum As Long, lpBuff As Long, nr As NETRESOURCE
Dim cbBuff As Long, cCount As Long
Dim p As Long, res As Long, i As Long
'Setup the NETRESOURCE input structure.
nr.dwUsage = RESOURCEUSAGE_CONTAINER
nr.lpRemoteName = 0
cbBuff = 1000
cCount = &HFFFFFFFF
'Open a Net enumeration operation handle: hEnum.
res = WNetOpenEnum(RESOURCE_CONNECTED, RESOURCETYPE_ANY, _
0, nr, hEnum)
If res = 0 Then
'Create a buffer large enough for the results.
'1000 bytes should be sufficient.
lpBuff = GlobalAlloc(GPTR, cbBuff)
'Call the enumeration function.
res = WNetEnumResource(hEnum, cCount, lpBuff, cbBuff)
If res = 0 Then
p = lpBuff
Cls
'WNetEnumResource fills the buffer with an array of
'NETRESOURCE structures. Walk through the list and print
'each local and remote name.
For i = 1 To cCount
CopyMemory nr, ByVal p, LenB(nr)
p = p + LenB(nr)
Print PointerToString(nr.lpLocalName), _
PointerToString(nr.lpRemoteName)
Next i
Else
MsgBox "Error: " & Err.LastDllError, vbOKOnly, _
"WNetEnumResources"
End If
If lpBuff <> 0 Then GlobalFree (lpBuff)
WNetCloseEnum (hEnum) 'Close the enumeration
Else
MsgBox "Error: " & Err.LastDllError, vbOKOnly, "WNetOpenEnum"
End If
End Sub
Private Function PointerToString(p As Long) As String
'The values returned in the NETRESOURCE structures are pointers to
'ANSI strings so they need to be converted to Visual Basic
Strings.
Dim s As String
s = String(255, Chr$(0))
CopyPointer2String s, p
PointerToString = Left(s, InStr(s, Chr$(0)) - 1)
End Function
返回
Set and Get
Cookies for a URL Using WinInet API
PRODUCT :Microsoft Visual Basic for Windows
PROD/VER:WINDOWS:5.0,6.0;
OPER/SYS:
KEYWORDS:kbVBp500 kbVBp600 kbInternet kbAPI kbWinInet kbInetDev
======================================================================
---------------------------------------------------------------------
The information in this article applies to:
- Microsoft Visual Basic Professional and Enterprise Editions for
Windows, versions 5.0, 6.0
---------------------------------------------------------------------
SUMMARY
=======
From a Visual Basic application, you can set and get cookies on a client
that corresponds to a given URL by using the InternetSetCookie and
InternetGetCookie APIs from the WinInet.dll.
MORE INFORMATION
================
1. Create a new standard .exe project in Visual Basic. Form1 is created
by
default.
2. Add the following controls to Form1:
Control Name Caption
--------------------------------------------------
Command Button Command1 InternetSetCookie
Command Button Command2 InternetGetCookie
3. In Form1, add the following code in the code window:
Option Explicit
' No more data is available.
Const ERROR_NO_MORE_ITEMS = 259
' The data area passed to a system call is too small.
Const ERROR_INSUFFICIENT_BUFFER = 122
Private Declare Function InternetSetCookie Lib "wininet.dll"
_
Alias "InternetSetCookieA" _
(ByVal lpszUrlName As String, _
ByVal lpszCookieName As String, _
ByVal lpszCookieData As String) As Boolean
Private Declare Function InternetGetCookie Lib "wininet.dll"
_
Alias "InternetGetCookieA" _
(ByVal lpszUrlName As String, _
ByVal lpszCookieName As String, _
ByVal lpszCookieData As String, _
lpdwSize As Long) As Boolean
Private Sub Command1_Click()
Dim bRet As Boolean
bRet = InternetSetCookie("http://xxxx/xxxx.htm", _
"Test", "Sent as Test via VB")
If bRet = False Then
MsgBox "Failed"
End If
End Sub
Private Sub Command2_Click()
Dim sCookieVal As String * 256
Dim bRet As Boolean
bRet = InternetGetCookie("http://xxxx/xxxx.htm", _
"Test", sCookieVal, 255)
If bRet = False Then
MsgBox "Failed"
Else
MsgBox sCookieVal
End If
End Sub
返回
Back to top
|