前段时间我问了这个问题,在这里解决了:
但是现在,由于未知原因,那里提供的 C# 或 Vb.Net 代码不起作用,我不明白为什么不能。
我对那里提供的原始代码进行了一些修改,但我测试了原始代码并没有工作。
发生的事情是我无法取消隐藏的过程,我不确定我在哪里失败了。乍一看,我认为我得到的句柄FindWindowEx
并不真正对应我想要的句柄。
这些是我的 P/Invoking 函数签名和显示窗口枚举:
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto,
BestFitMapping:=False, ThrowOnUnmappablechar:=True)>
Friend Shared Function FindWindow(
ByVal lpClassName As String,
ByVal lpWindowName As String
) As IntPtr
End Function
<DllImport("User32.dll", SetLastError:=True, CharSet:=CharSet.Auto,
BestFitMapping:=False, ThrowOnUnmappablechar:=True)>
Friend Shared Function FindWindowEx(
ByVal hwndParent As IntPtr,
ByVal hwndChildAfter As IntPtr,
ByVal strClassName As String,
ByVal strWindowName As String
) As IntPtr
End Function
<DllImport("user32.dll")>
Friend Shared Function GetWindowThreadProcessId(
ByVal hWnd As IntPtr,
ByRef processId As Integer
) As Integer
End Function
<DllImport("User32", SetLastError:=False)>
Friend Shared Function ShowWindow(
ByVal hwnd As IntPtr,
ByVal nCmdShow As ProcessUtil.WindowState
) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
Public Enum WindowState As Integer
Hide = 0
Normal = 1
ShowMinimized = 2
Maximize = 3
ShowMaximized = Maximize
ShowNoActivate = 4
Show = 5
Minimize = 6
ShowMinNoActive = 7
ShowNA = 8
Restore = 9
ShowDefault = 10
ForceMinimize = 11
End Enum
功能:
Public Function SetWindowState(ByVal p As Process,
ByVal windowState As ProcessUtil.WindowState) As Boolean
Dim pHandle As IntPtr = IntPtr.Zero
Dim pid As Integer
' If window is visible then...
If (p.MainWindowHandle <> IntPtr.Zero) Then
Return ProcessUtil.NativeMethods.ShowWindow(p.MainWindowHandle, windowState)
Else ' window is hidden.
' Check all open windows (not only the process we are looking),
' begining from the child of the desktop.
While (pid <> p.Id)
' Get child handle of window who's handle is "pHandle".
pHandle = NativeMethods.FindWindowEx(IntPtr.Zero, pHandle, Nothing, Nothing)
' Get PID from "pHandle".
NativeMethods.GetWindowThreadProcessId(pHandle, pid)
End While
Return NativeMethods.ShowWindow(pHandle, windowState)
End If
End Function
以及我尝试测试该功能的方式,首先我隐藏记事本进程的窗口,然后尝试取消隐藏它。
Dim p As Process = Process.GetProcessesByName("notepad").First
ProcessUtil.SetWindowState(p, ProcessUtil.WindowState.Hide)
' I find again the process to renew the "p.MainWindowHandle" as IntPtr.Zero.
p = Process.GetProcessesByName("notepad").First
ProcessUtil.SetWindowState(p, ProcessUtil.WindowState.Restore)