看板 Visual_Basic 關於我們 聯絡資訊
Private Declare Function OpenProcess Lib "kernel32" _ (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, _ ByVal dwProcessId As Long) As Long Private Declare Function WaitForSingleObject Lib "kernel32" _ (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long Private Declare Function CloseHandle Lib "kernel32" _ (ByVal hObject As Long) As Long Private Declare Function GetExitCodeProcess Lib "kernel32" _ (ByVal hProcess As Long, lpExitCode As Long) As Long Private Declare Function TerminateProcess Lib "kernel32" _ (ByVal hProcess As Long, ByVal uExitCode As Long) As Long Private Declare Function GetForegroundWindow Lib "user32" () As Long Private Declare Function IsWindow Lib "user32" _ (ByVal hwnd As Long) As Long Const PROCESS_QUERY_INFORMATION = &H400 Const SYNCHRONIZE = &H100000 Const STILL_ALIVE = &H103 Const INFINITE = &HFFFF Private ExitCode As Long Private hProcess As Long Private isDone As Long Private Sub CommandButton1_Click() Dim pid As Long pid = Shell("c:\ping.bat", vbNormalFocus) hProcess = OpenProcess(PROCESS_QUERY_INFORMATION + SYNCHRONIZE, 0, pid) ExitEvent = WaitForSingleObject(hProcess, 1000) '不加這一行還不會停ㄟ Call CloseHandle(hProcess) TerminateTask ("C:\WINDOWS\system32\cmd.exe") '感覺好像有點笨ㄟ End Sub 以下為模組 Declare Function EnumWindows Lib "user32" (ByVal wndenmprc As Long, ByVal lParam As Long) As Long Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long Public Const WM_CLOSE = &H10 Private Target As String Public i As Integer ' Check a returned task to see if we should ' kill it. Public Function EnumCallback(ByVal app_hWnd As Long, ByVal param As Long) As Long Dim buf As String * 256 Dim title As String Dim length As Long ' Get the window's title. length = GetWindowText(app_hWnd, buf, Len(buf)) title = Left$(buf, length) ' See if this is the target window. If InStr(title, Target) <> 0 Then ' Kill the window. SendMessage app_hWnd, WM_CLOSE, 0, 0 End If ' Continue searching. EnumCallback = 1 End Function ' Ask Windows for the list of tasks. Public Sub TerminateTask(app_name As String) Target = app_name EnumWindows AddressOf EnumCallback, 0 End Sub 這個方法可以關掉,但我是自己看到視窗名稱為C:\WINDOWS\system32\cmd.exe 不知道能不能用pid取得視窗名稱? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.217.62.188
fumizuki:用視窗名稱是最不安全的作法 01/20 09:09
fumizuki:而且你不是已經用 GetWindowText 取得視窗名稱了嗎 01/20 09:14
fumizuki:還有跟 C:\WINDOWS\system32\cmd.exe作比對才 send close 01/20 09:14
fumizuki:GetWindowThreadProcessId(hwnd, pid) 01/20 09:16
fumizuki:這個可以找到 hwnd 所屬的pid 01/20 09:16
macgyfu:謝啦 我想我大概知道了 01/20 14:09