在VB中调用API函数

在VB中调用API函数

 API函数大多在windows/system32/user32文件夹的kernel等动态链接库文件中,现在列举一个需要调用API函数的程序(本例程序使用的工具是VB)来简单介绍一下如何在程序中调用API。

1、首先在VB中新建一个标准EXE的工程,如下图所示。
在这里插入图片描述
2、在控件工具条中拖放一个Label,将其属性名改为“修改系统时间”;拖放一个Frame,将其左上角的“Frame1”改为“修改时间”;依次拖放3个TextBox,将其Text设为空(即删掉Text1,Text2,Text3),并将(名称)依次改为Texthour,Textmin,Textsec(后面写代码需要用到);再依次拖放3个Label,将其属性名改为“时”、“分”、“秒”;拖放两个CommandButton,将其Caption属性改为“确定”和“取消”。Form1窗口设计如下图所示。
在这里插入图片描述
3、下面是Form1窗口对应的代码,在通用中声明GetSystemTime和SetSystemTime两个API函数。

Option Explicit
Private Declare Sub GetSystemTime Lib "kernel32" (lpTime As SYSTEMTIME)
Private Declare Function SetSystemTime Lib "kernel32" (lpTime As SYSTEMTIME) As Long
Private Type SYSTEMTIME
        wYear As Integer
        wMonth As Integer
        wDayOfWeek As Integer
        wDay As Integer
        wHour As Integer
        wMinute As Integer
        wSecond As Integer
        wMilliseconds As Integer
End Type
Dim time As SYSTEMTIME
Private Sub Command1_Click()
Dim hour As Integer
hour = Texthour.Text - 8    '北京时间
With time
    .wHour = IIf(hour > 0, hour, hour + 24)    '世界时间
    .wMinute = Textmin.Text
    .wSecond = Textsec.Text
End With
SetSystemTime time
End Sub

Private Sub Command2_Click()
Unload Form1
End Sub
Private Sub Form_Load()
    GetSystemTime time
    With time
        Texthour.Text = .wHour + 8    '北京时间
        Textmin.Text = .wMinute
        Textsec.Text = .wSecond
    End With   
End Sub

在这里插入图片描述
4、点击“运行 | 启动”后的结果如下图所示。
在这里插入图片描述
5、修改系统时间,如下图所示。
在这里插入图片描述
6、修改后发现系统时间已经更改,如下图所示。
在这里插入图片描述
说明:

1、声明API函数的方法为:Declare Function (或Sub)API函数名称lib dll文件名(该dll中包含需要声明的API函数)(参数)。
2、如本例中,SetSystemTime为声明的API函数名称,它所在的dll文件名为kernel,lib为固定语法结构,意思为lib前面的API函数包含在其后的dll文件中。现在声明SetSystemTime这个API函数的时候,就可以写成:Declare Function SetSystemTime Lib “kernel32” (lpTime As SYSTEMTIME) As Long。
3、一般在写程序时,需要用到API函数,就必须对其声明。
4、当声明成功后,就可以在窗口登录时通过GetSystemTime得到当前系统时间,再将其赋予3个文本框(分别代表时、分、秒)。在“确定”按钮事件中,将3个文本框中的数据通过SetSystemTime函数赋予系统。
5、通过本例子说明一下声明API函数的方法以及如何调用API函数,对API函数及其使用方法有个初步的了解,要想深入学习API函数,还需要更多时间做些实验,在实验中不断提高对API函数掌握的熟练程度。

猜你喜欢

转载自blog.csdn.net/qq_46649692/article/details/109045000