斯是陋室,唯吾德馨
判断应用程序是否仍在运行并设置焦点
上一篇 / 下一篇 2006-08-16 11:30:09 / 天气: 晴朗 / 心情: 高兴 / 个人分类:网摘精选
查看( 576 ) /
评论( 2 )
-
超能刷发布于2006-08-16 11:38:09
-
CODE:
请将下面的代码放置在模块中:
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%)
' get window word constants
Const GWW_HWNDPARENT = (-8)
' get window constants
Const GW_HWNDFIRST = 0
Const GW_HWNDNEXT = 2
'---
-
' 函数: Get_Other_Instance:布尔型, 参数( inhwnd Inputonly, outhwnd
Outputonly)
' 目的: 获得要检测程序的另一个实例的窗口句柄。
'
' 描述: 同其它例子不同的是:该程序能检测哪些在运行时改变主窗口标题的程序,
如MS WORD
' 实现的方法是利用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 Not app.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) ' get the first window
in the window list
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 "Application is already running. Switching to existing
Application"
SetFocusAPI otherhwnd%
End
End If
End Sub
-
jhkdiy
发布于2006-08-16 14:13:15
-
CODE:
MsgBox "Application is already running. Switching to existing Application"个人的建议:
SetFocusAPI otherhwnd%
SetFocus API 只是设置了键盘输入焦点给指定的窗口,并不能将该窗口调到为顶层窗口(即当前活动窗口),如果要实现将指定的窗口设为当前活动窗口可以使用SetForegroundWindow()函数,同样传递一个窗口句柄给它既可实现。这样做可以做到真正意义上的激活。
标题搜索
日历
|
|||||||||
| 日 | 一 | 二 | 三 | 四 | 五 | 六 | |||
| 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 | |||||||||
我的存档
数据统计
- 访问量: 67279
- 日志数: 121
- 图片数: 27
- 建立时间: 2006-07-15
- 更新时间: 2007-12-18

