苏教版声音的传播教案:vb判断应用程序是否仍在运行并设置焦点

来源:百度文库 编辑:偶看新闻 时间:2024/04/27 19:36:01

下面的程序将利用VB程序的一个独有的特点:隐藏的父窗口。每一个VB应用程序都有一个隐藏的父窗口。该父窗口的标题(Caption)就是你在“生成EXE”文件时所提供的应用程序的名称。这就是为什么当你按下Ctl+Alt+Del查看时,任务列表中显示的总是应用程序的名称,而不是程序主窗口窗口的标题。
   既然父窗口是隐藏的,那我们就没有必要去改变父窗口的标题。结果是,几乎所有的VB程序都可以用下面的小程序。
   请注意,有一类程序不能应用下面这段小程序:如果你在“生成EXE”文件时,将应用程序的名称设置成为零字符,那么这段程序就无效了。这是因为很多很多窗口都将其标题设为零字符。
   另一个需要注意的地方就是:该程序用到了App.Previnstance来检查程序的另一个实例正在运行。这样做可以提高程序的效率,但代价是你不能同时运行两个或以上的要检查的程序。如果你想这样做的话,请将有App.Previnstance的那一行语句注释掉。

请将下面的代码放置在模块中:
Declare Function GetWindowWord% Lib "User"(ByVal hWnd%,ByVal nIndex%)
Declare Function GetWindowText% Lib "User"(ByVal hWnd%,ByVal lpString$,ByVal aint%)
Declare Function GetWindowTextLength% Lib "User"(ByVal hWnd%)
Declare Function GetWindow% Lib "User"(ByVal hWnd%,ByVal wCmd%)
Declare Function SetFocusAPI% Lib "User" Alias "SetFocus"(ByVal hWnd%)
'getwindowwordconstants
Const GWW_HWNDPARENT=(-8)
'getwindowconstants
Const GW_HWNDFIRST=0
Const GW_HWNDNEXT=2

'函数:Get_Other_Instance:布尔型,参数(inhwndInputonly,outhwndOutputonly)
'目的:获得要检测程序的另一个实例的窗口句柄。
'描述:同其它例子不同的是:该程序能检测哪些在运行时改变主窗口标题的程序,如MSWORD
'实现的方法是利用VB程序独有的特点,即:每一个VB程序在运行时都会产生一个隐藏的父窗口。该父窗口的标题就是
'你在生成EXE文件时所输入的程序名。VB程序员很少改变这些字符,并且用户看不到该父窗口。
'输入:inhwnd--被叫窗口的窗口句柄
'输出:如果窗口被找到则为真,否则为假。
'outhwnd--0或设为另一个窗体的父窗口的hwnd

Public Function get_other_instance(ByVal inhwnd As Integer,outhwnd As Integer) As Integer
Dim parent%,nlen%,ptext$,nexthwnd%,wtext$
get_other_instance=False
outhwnd=0
If Notapp.PrevInstance Then
Exit Function
parent%=GetWindowWord(inhwnd,GWW_HWNDPARENT)
nlen%=GetWindowTextLength(parent%)+2
ptext$=Space$(nlen%)
nlen%=GetWindowText(parent%,ptext$,nlen%)
ptext$=Left$(ptext$,nlen%)
nexthwnd%=GetWindow(parent%,GW_HWNDFIRST)'getthefirstwindowinthewindowlist
Do While nexthwnd%>0
nlen%=GetWindowTextLength(nexthwnd%)+2
wtext$=Space$(nlen%)
nlen%=GetWindowText(nexthwnd%,wtext$,nlen%)
wtext$=Left$(wtext$,nlen%)
If wtext$=ptext$ And nexthwnd%<>parent% Then
get_other_instance=True
outhwnd=nexthwnd%
Exit Do
End If
nexthwnd%=GetWindow(nexthwnd%,GW_HWNDNEXT)
Loop
End Function
将下述代码放在窗体的Load事件中
Sub Form_Load()
Dim otherhwnd%
If Get_Other_Instance(Hwnd,otherhwnd%) then
MsgBox"Applicationisalreadyrunning.SwitchingtoexistingApplication"
SetFocusAPIotherhwnd%
End
End If
End Sub
查看GetWindow,GetWindowWord,GetWindowText,GetWindowTextLength,SetFocusAPI的用法