我有两个函数可以在给出Window Title时获取应用程序的PID,并在给出PID时获取应用程序的Window Title。这些函数工作正常,但我觉得它们比其他函数慢一点,因为这些函数都写入外部文本文件以获得CMD输出。
功能:
在给出Window Title时获取PID:
Function IntProcessID(StrWindowTitle)
Dim FSO, WshShell, Tasks, TA, TList, TN, Result
If StrComp(StrWindowTitle, "", 1) <> 0 Then
On Error Resume Next
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
TN = FSO.GetTempName
FSO.GetFolder(WshShell.ExpandEnvironmentStrings("%LOCALAPPDATA%") + "/Temp").CreateTextFile(TN).Close
Set TList = FSO.GetFile(WshShell.ExpandEnvironmentStrings("%LOCALAPPDATA%") + "/Temp/" + TN)
Result = WshShell.Run("CMD /C TASKLIST /V /FI ""WINDOWTITLE eq " + StrWindowTitle + """ /FO CSV > """ + TList.Path + """", 0, True)
If Result = 0 Then
TList.Attributes = 22
Tasks = Split(FSO.OpenTextFile(TList.Path).ReadAll, VbCrLf)
For Each Task In Tasks
TA = Split(Trim(Task), ",")
If UBound(TA) > 0 Then
If StrComp(CStr(TA(UBound(TA) + 0)), """" + StrWindowTitle + """", 1) = 0 Then
IntProcessID = Replace(CStr(TA(LBound(TA) + 1)), """", "")
End If
End If
Next
Else
MsgBox "TASKLIST command failed, Error " + CStr(Result)
End If
FSO.DeleteFile TList.Path, True
If Err <> 0 Then
MsgBox "DeleteFile failed, Error " + CStr(Err) + " - " + CStr(Err.Description)
Err.Clear
End If
Else
MsgBox "The Window Title cannot be empty"
End If
End Function
在给出PID时获取窗口标题:
Function StrWindowTitle(IntProcessID)
Dim FSO, WshShell, Task, TA, TList, TN, Result
If StrComp(CStr(IntProcessID), "", 1) <> 0 Then
On Error Resume Next
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
TN = FSO.GetTempName
FSO.GetFolder(WshShell.ExpandEnvironmentStrings("%LOCALAPPDATA%") + "/Temp").CreateTextFile(TN).Close
Set TList = FSO.GetFile(WshShell.ExpandEnvironmentStrings("%LOCALAPPDATA%") + "/Temp/" + TN)
Result = WshShell.Run("CMD /C TASKLIST /V /FI ""PID eq " + CStr(IntProcessID) + """ /FO CSV > """ + TList.Path + """", 0, True)
If Result = 0 Then
TList.Attributes = 22
Task = Split(FSO.OpenTextFile(TList.Path).ReadAll, VbCrLf)
TA = Split(Trim(Task(1)), ",")
If UBound(TA) > 1 Then
If StrComp(CStr(TA(LBound(TA) + 1)), """" + CStr(IntProcessID) + """", 1) = 0 Then
StrWindowTitle = Replace(CStr(TA(UBound(TA) + 0)), """", "")
End If
End If
Else
MsgBox "TASKLIST command failed, Error " + CStr(Result)
End If
FSO.DeleteFile TList.Path, True
If Err <> 0 Then
MsgBox "DeleteFile failed, Error " + CStr(Err) + " - " + CStr(Err.Description)
Err.Clear
End If
Else
MsgBox "The Process ID cannot be empty"
End If
End Function
这里我使用带有Run
方法的外部文本文件来隐藏控制台窗口。
请告诉我可能的方法,使这两个功能更短,更快,更可靠,更稳定,而不会在运行时闪烁任何CMD /控制台窗口。