我正在尝试创建一个通用函数来获取进程的主窗口句柄,给进程句柄,我想使用 LINQ(避免使用 FOR)但它在“Where”处引发“拒绝访问”异常’条款。
我做错了什么?
Private Function Get_Process_MainWindowHandle(ByVal ProcessHandle As IntPtr) As IntPtr
Try
Return Process.GetProcesses _
.Where(Function(p) p.Handle.Equals(ProcessHandle)) _
.Cast(Of Process) _
.First _
.MainWindowHandle
Catch ex As Exception
MsgBox(ex.Message) ' ex Message: Access denied
Return IntPtr.Zero
End Try
End Function
用法:
Get_Process_MainWindowHandle(Process.GetProcessesByName("calc").First.Handle)
更新:
在我试图做的另一个函数中,我得到了同样的异常,更重要的是,找不到主窗口句柄,我做错了什么?:
Private Sub Resize_Process_Window(ByVal ProcessHandle As IntPtr, _
ByVal Weight As Integer, _
ByVal Height As Integer)
Dim rect As Rectangle = Nothing
Dim procs As Process() = Nothing
Dim hwnd As IntPtr = IntPtr.Zero
Try
' Find the process
procs = Process.GetProcesses
For Each p As Process In procs
Try
If p.Handle.Equals(ProcessHandle) Then
MsgBox("Handle found!") ' Msgbox will never be displayed :(
hwnd = p.MainWindowHandle
Exit For
End If
Catch : End Try ' Catch for 'Denied acces' Win32Exception.
Next
Msgbox(hwnd) ' hwnd always is '0' :(
' Store the Left, Right, Bottom and Top positions of Window, into the Rectangle.
GetWindowRect(hwnd, rect)
' Resize the Main Window
MoveWindow(hwnd, rect.Left, rect.Top, Weight, Height, True)
Catch ex As InvalidOperationException
'Throw New Exception("Process not found.")
MessageBox.Show("Process not found.", Nothing, MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
rect = Nothing
procs = Nothing
hwnd = Nothing
End Try
End Sub
用法:
Resize_Process_Window(Process.GetProcessesByName("notepad").First.Handle, 500, 500)