【VB】常用的一些方法

本文由多篇[旧博客]组合迁移。文章一文章二文章三文章四

VB精确延时API

1
2
3
4
5
6
7
'延时
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Private Sub Form_Load()
'延时1秒=1000毫秒
sleep(1000)
End Sub

VB输入框只允许输入数字

1
2
3
4
Private Sub txSN_KeyPress(KeyAscii As Integer)
Const xStr As String = "0123456789"
KeyAscii = IIf(InStr(xStr & Chr(8), Chr(KeyAscii)), KeyAscii, 0)
End Sub

webbrowser里的js与VB自定义事件的交互

在VB程序中放置webbrowser控件,如果加载的页面页面上有以下语句:

1
<a onclick=VBScript:document.title="VB:test('X','Y','Z')">文字</a>

如果想在VB程序里面捕获自定义事件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
Option Compare Text

Private Function Test(S1, S2, S3)
MsgBox S1 & S2 & S3
End Function

Private Sub Form_Load()
WebBrowser1.Navigate "e:\1.htm"
End Sub

Private Sub WebBrowser1_TitleChange(ByVal Text As String)
If Left(Text, 3) = "VB:" Then
Dim s As String
Dim fncName As String
Dim l As Long
Dim args
s = Mid(Text, 4)
s = Replace(s, "(", " ")
s = Replace(s, ")", " ")
l = InStr(s, " ")

fncName = Trim(Left(s, l - 1))
args = Split(Mid(s, l), ",")

For i = 0 To UBound(args)
args(i) = Trim(args(i))
Next

Select Case fncName
Case "test"
Test args(0), args(1), args(2)
End Select
Else
Caption = Text
End If
End Sub

使用Webbrowser直接输出HTML代码

1
2
3
4
5
6
7
8
Private Sub Form_Load()
Me.WebBrowser1.Navigate2 "about:blank"
Do
DoEvents
Loop Until Me.WebBrowser1.ReadyState = READYSTATE_COMPLETE

WebBrowser1.Document.Write "<body style='padding:0; margin:0;'><img src='https://www.baidu.com/img/baidu_jgylogo3.gif'></body>"
End Sub