VB判断程序是否已经运行2008/06/24 20:55'作用: 判断是否已经运行,如果已运行显示该程序!
'新建一个工程,在Form1窗体的代码如下:
Option Explicit
Private Const HWND_TOPMOST = -1
Private Const SWP_NOSIZE = &H1
Private Const SWP_NOMOVE = &H2
Private Const SW_RESTORE = 9
Private Declare Function SetWindowPos Lib "user32.dll" (ByVal lhwnd As Long, ByVal hWndInsertAfter As Long, ByVal swpX As Long, ByVal swpY As Long, ByVal cX As Long, ByVal cY As Long, ByVal wFlags As Long) As Long
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Sub Form_Load()
Dim lngWindow As Long
If App.PrevInstance Then
MsgBox "程序已运行。", vbInformation, "提示信息"
lngWindow = FindWindow(vbNullString, "测试窗口")
If lngWindow <> 0 Then
ShowWindow lngWindow, SW_RESTORE
SetWindowPos lngWindow, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE
End If
End
End If
Me.Caption = "测试窗口"
End Sub
其实原理很简单,利用FindWindow函数根据窗体的标题来寻找,如果找到,则返回该程序的句柄,得到句柄后,就可以为所欲为了!
ShowWindow lngWindow, SW_RESTORE
这个API的作用,是防止窗体如果隐藏了,则把它显示出来
SetWindowPos的作用,是让窗体显示在最上方,如果把HWND_TOPMOST换成-2(HWND_NOTOPMOST),则窗体取消显示在最上方。
不过这样的话,你就要保证你的程序的标题是独一无二的才行。如果不保证是不是独一无二,可以使用FindWindowEx函数重复查找符合条件的窗体!