如何在VB程序中重复利用一段代码

如何在VB程序中重复利用一段代码,第1张

把重复利用的一段代码写成函数,调用即可,给你举个例子:

Private Sub Command1_Click()

dim i,j

j = Format(Dec_to_Bin((i + 65536)), "0000000000000000") '调用函数

End Sub

Public Function Dec_to_Bin(ByVal Dec As Long) As String '重复利用的代码写成函数

Dec_to_Bin = ""

Do While Dec > 0

    Dec_to_Bin = Dec Mod 2 & Dec_to_Bin

    Dec = Dec \ 2

Loop

End Function

vb中只允许运行一个程序实例的方法 利用vb中的App.PrevInstance即可,然后利用AppActivate来将前一个程序呼到前台.

Private Sub Main()If App.PrevInstance Then'程序是否已运行Dim Title As StringTitle = App.TitleApp.Title = "The Sec"On Error Resume NextAppActivate TitleExit SubEnd If

...... '正常运行时的代码

End Sub

这样写的话,如果前一个程序窗口为Hide,就不会将窗口显示并提前,如果要让窗口为隐藏的时候也可以让窗口提前,则需要获得窗口的hwnd,然后将窗口先显示出来.

先声明两个api,及相关的常量:

Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As LongDeclare Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long

Public Const SW_HIDE = 0Public Const SW_SHOWNORMAL = 1Public Const SW_NORMAL = 1Public Const SW_SHOWMINIMIZED = 2Public Const SW_SHOWMAXIMIZED = 3Public Const SW_MAXIMIZE = 3Public Const SW_SHOWNOACTIVATE = 4Public Const SW_SHOW = 5Public Const SW_MINIMIZE = 6Public Const SW_SHOWMINNOACTIVE = 7Public Const SW_SHOWNA = 8Public Const SW_RESTORE = 9Public Const SW_SHOWDEFAULT = 10Public Const SW_FORCEMINIMIZE = 11Public Const SW_MAX = 11

然后改写代码:

Private Sub Main()If App.PrevInstance Then'程序是否已运行Dim Title As StringTitle = App.TitleApp.Title = "The Sec"On Error GoTo FirstHideAppActivate TitleExit SubEnd If

...... '正常运行时的代码

Exit SubFirstHide:Dim hwnd As Longhwnd = FindWindow(vbNullString, Title)If hwnd <>0 ThenShowWindow hwnd, SW_SHOWNORMALAppActivate TitleEnd IfEnd Sub

这样,当窗口为Hide的时候,程序将跳转到错误处理语句FirstHide处,获得前一个窗口的句柄并显示窗口,然后再利用AppActivate将窗口提到前台.

退出时d出提示 退出?

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer) Dim strExit As String If UnloadMode <>vbAppWindows Then strExit = "您确定要停止运行吗?" If vbNo = MsgBox(strExit, vbQuestion Or vbYesNo, "") Then Cancel = True Exit Sub End If End If End End Sub


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/10880317.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-12
下一篇 2023-05-12

发表评论

登录后才能评论

评论列表(0条)

保存