使用WinAPI的FindWindow判斷程式是否運行
一、問題說明
如何透過 WinAPI中的 FindWindow 來判斷 該程式 是否在運行
二、方法
Windows API 中的 FindWindws : 尋找指定視窗類別、名稱之視窗代號 (hWnd) ,使用方式相當簡單,先調用此函數

接著透過以下程式碼,修改 "程式名稱" 即可








三、範例
以下程式碼的功能為程式執行時會開啟 Form1 與 Form2 , Form2 在三秒後關閉,而 Form2 的執行與否將會顯示在 Form1 的 Label1 中
Form1 程式碼
01
Public Class Form1
02
03
Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer
04
05
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
06
Dim f2 As New Form2
07
f2.TopMost = False
08
f2.Show()
09
10
Timer1.Interval = 100
11
Timer1.Enabled = True
12
End Sub
13
14
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
15
Dim hwd1 As IntPtr
16
hwd1 = FindWindow(vbNullString, "Form2")
17
18
If hwd1.Equals(IntPtr.Zero) Then
19
Label1.Text = "該程式未運行"
20
Else
21
Label1.Text = "該程式已運行"
22
End If
23
24
End Sub
25
End Class

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

Form2
01
Public Class Form2
02
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
03
Timer1.Interval = 3000
04
Timer1.Enabled = True
05
End Sub
06
07
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
08
Me.Close()
09
End Sub
10
End Class

02

03

04

05

06

07

08

09

10

四、執行結果
五、參考
發問問題網址
http://www.blueshop.com.tw/board/show.asp?subcde=BRD20090424235959DUF&fumcde=